2010-06-18 39 views
4

我想弄清楚如何從另一個類調用函數。我使用的是RootViewController的設置自己的看法作爲一個可以說AnotherViewController從另一個類調用函數 - Obj C

所以在我AnotherViewController即時將添加在.h文件

@class RootViewController 

而在.m文件即時將導入查看

#import "RootViewController.h" 

我有一個調用的函數:

-(void)toggleView { 
//do something } 

然後在我的AnotherViewController我分配了一個按鈕:

-(void)buttonAction { 
//} 

在我想能夠調用該函數toggleView在我的RootViewController的的buttonAction。

有人可以澄清我如何做到這一點。

我嘗試添加這是我buttonAction:

RootViewController * returnRootObject = [[RootViewController alloc] init]; 
    [returnRootObject toggleView]; 

但我不認爲這是正確的。

謝謝先進。

回答

1

你會想在你的AnotherViewController中創建一個委託變量,當你從RootViewController初始化它時,將RootViewController的實例設置爲AnotherViewController的委託。

爲此,請向AnotherViewController添加一個實例變量:「id delegate;」。然後,添加了兩種方法來AnotherViewController:

- (id)delegate { 
    return delegate; 
} 

- (void)setDelegate:(id)newDelegate { 
    delegate = newDelegate; 
} 

最後,在RootViewController的,無論AnotherViewController被初始化,做

[anotherViewControllerInstance setDelegate:self]; 

然後,當您要執行toggleView,做

[delegate toggleView]; 

或者,你可以讓你的RootViewController成爲單例,但是委託方法當然是更好的做法。我還想指出,我剛纔告訴你的方法是基於Objective-C 1.0的。 Objective-C 2.0有一些新的屬性,但是當我學習Obj-C時,這讓我困惑不已。在查看屬性之前,我會獲得1.0的優先級(這樣你就會明白他們先做什麼,他們基本上只是自動讓getter和setter)。

1

我試用了NSNotificationCentre - 像魅力一樣工作 - 感謝您的回覆。我無法得到它的運行,但NS已經得到它的轟鳴。

[[NSNotificationCenter defaultCenter] postNotificationName:@"switchView" object: nil]; 
+0

這不是最有效的方法,完全通過NSNotificationCenter處理類間通信確實不是很好的做法。我真的建議你看一下委託方法或者至少一個單例。 – AriX 2010-06-21 01:27:06