2012-05-26 50 views
0

我想隐藏一个对象在我的viewController中,从自定义类中执行代码,但对象为零。隐藏另一个类的对象

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是零

#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]; 
} 

任何想法?

回答

0

你的UILabel是零,因为你刚刚初始化你的控制器,但没有加载它的视图。您首次请求访问绑定视图时,您的控制器的IBoutlet会自动从xib或故事板中实例化,因此为了访问它们,您首先必须通过某种方式加载其视图。

编辑(OP意见后):

因为你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]; 
} 
+0

谢谢您的回答,但viewDidLoad中被前执行。我通过在viewDidLoad中放入NSLog(@“View Did Load”)来测试它,并在得到“nil 1”之前得到它。 我应该重新加载FirstViewController吗?我怎么能这样做? – CostasKal

+0

尝试将'alloc init'改为'alloc initWithNibName:bundle:' – Alladinian

+0

尝试initWithNibName:@“FirstViewController”bundle:nil。仍然不起作用:( – CostasKal