2010-11-16 63 views
2

我知道這是一個常見的問題,我用Google搜索了很多,似乎沒有得到運氣來解決我的問題。 我有一個@interface TestViewController:的UIViewController 並在其實現文件我定義了一個方法:視圖控制器可能會不響應to'method」問題

-(void)method1 { 
    do something; 
    [self method1];//here I need to call the method itself if a statement is true and this line is where the warning TestViewController may not respond to'method1' I got 
} 

-(void)method2{ 
    [self method1] //But there is no problem with this line 
} 

誰能幫助我? 在此先感謝!

回答

4

你的方法聲明中缺少頭。 只需添加

-(void)method1; 
-(void)method2; 

您TestViewController.h文件

更新:

你之所以沒有得到關於第二個電話([self method1]方法2中)的警告是,編譯器在那個時候已經知道了method1。 (因爲執行發生在method2之前)

1

Objective-C就像C使用單通編譯器收集所有已知符號一樣。結果是你只能引用在當前範圍之上聲明的方法和變量。

可以解決你給的三種方式的例子這方面的問題:

添加method1的公共接口在頭文件中,就像@weichsel建議。

如果你想method1私人那麼你可以通過它在頂部的你實現文件中聲明未命名的類別添加到您的類。就像這樣:

#import "Foo.h" 
@interface Foo() 
-(void)method1; 
@end 

@implementation Foo 
    // ... lots of code as usual ... 
@end 

第三個選項可以被看作是由一些黑客,但它確實是Objective-C語言的一個特徵。就像所有方法都獲得名爲self的隱式變量(該方法被調用的實例),所有方法alsa都會獲得名爲_cmd的隱式變量,該類型的變量類型爲SEL,它是用於調用此方法的選擇器。這可以用來快速再次調用同樣的方法:

-(void)method1 { 
    if (someContition) { 
    [self performSelector:_cmd withObject:nil]; 
    } else { 
    // Do other stuff... 
    } 
} 

如果你想確保一個特定的方法總是在主線程中執行,這是最有用:

-(void)method { 
    if (![NSThread isMainThread]) { 
    [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO]; 
    return; 
    } 
    // Do stuff only safe on main thread 
} 
+0

感謝這樣的明確的解釋! – 4everafk 2010-11-16 19:30:21