【问题标题】:hide an object from another class隐藏另一个类的对象
【发布时间】:2012-05-26 15:48:55
【问题描述】:

我试图在我的 viewController 中隐藏一个对象,代码从自定义类执行,但该对象为 nil。

FirstViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController {
    IBOutlet UILabel *testLabel;
}

@property (nonatomic, retain) IBOutlet UILabel *testLabel;

- (void) hideLabel;

FirstViewController.m 我合成了 testLabel,我有一个隐藏它的功能。如果我从 viewDidAppear 调用该函数,它可以工作,但我想从我的其他类调用它。当从其他类调用时,testLabel 为 nil

#import "FirstViewController.h"
#import "OtherClass.h"

@implementation FirstViewController
@synthesize testLabel;

- (void) hideLabel {
    self.testLabel.hidden=YES;
    NSLog(@"nil %d",(testLabel==nil)); //here I get nil 1 when called from OtherClass
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    OtherClass *otherClass = [[OtherClass alloc] init];
    [otherClass hideThem];
    //[self hideLabel]; //this works, it gets hidden
}

OtherClass.h

@class FirstViewController;

#import <Foundation/Foundation.h>

@interface OtherClass : NSObject {
    FirstViewController *firstViewController;
}

@property (nonatomic, retain) FirstViewController *firstViewController;

-(void)hideThem;

@end

OtherClass.m 调用 FirstViewController 中的 hideLabel 函数。在我的原始项目中,(这显然是一个例子,但原始项目正在工作)我在这里下载了一些数据,我想在下载完成后隐藏我的加载标签和指示器

#import "OtherClass.h"
#import "FirstViewController.h"

@implementation OtherClass
@synthesize firstViewController;

-(void)hideThem {
    firstViewController = [[FirstViewController alloc] init];
    //[firstViewController.testLabel setHidden:YES]; //it doesn't work either
    [firstViewController hideLabel];
}

有什么想法吗?

【问题讨论】:

    标签: xcode


    【解决方案1】:

    您的UILabel 为 nil,因为您刚刚初始化了控制器但没有加载它的视图。当您第一次请求访问绑定视图时,控制器的 IBoutlets 会自动从 xib 或情节提要中实例化,因此为了访问它们,您首先必须通过某种方式加载其视图。

    编辑(在 OP cmets 之后):

    由于您的FirstViewController 已经初始化并且您的OtherClass 已由该控制器实例化,您可以只持有对它的引用而不尝试初始化新的。 所以尝试这样的事情:

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        OtherClass *otherClass = [[OtherClass alloc] init];
        otherClass.firstViewController = self;
        [otherClass hideThem];
    }
    

    在您的 OtherClass.m 中:

    -(void)hideThem {
        [self.firstViewController hideLabel];
    }
    

    【讨论】:

    • 谢谢你的回答,但是viewDidLoad之前已经执行过了。我通过将 NSLog(@"View Did Load") 放入 viewDidLoad 对其进行了测试,并且在获得“nil 1”之前得到了它。我应该重新加载 FirstViewController 吗?我怎么能这样做?
    • 尝试将您的alloc init 更改为alloc initWithNibName:bundle:
    • 试过 initWithNibName:@"FirstViewController" bundle:nil。还是不行:(
    • 您是想通过您的OtherClass 显示您的FirstViewController 还是它已经加载并且您只想调用它的方法?另外,你在哪里实例化你的 OtherClass
    • FirstViewController 已加载。我叫 [otherClass hideThem];在 FirstViewController 的 viewDidAppear 中,我也实例化了 OtherClass。我调用 [firstViewController hideLabel];来自我的其他班级
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多