2012-05-26 49 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