2012-06-07 18 views
1

我想用類方法選擇UIBarButtonItem的動作。iPhone:我可以使用UIBarButtonItem的動作選擇器的類方法嗎?

的代碼是:

[[UIBarButtonItem alloc] 
    initWithTitle:@"title"            
    style:UIBarButtonItemStylePlain 
    target: self 
    action:@selector(method)] 

當我使用實例方法的行動,它的工作原理。

但是當我使用類方法進行操作時,當我點擊按鈕時會發生錯誤。
錯誤消息是:unrecognized selector sent to instance

我不能使用類方法嗎?
我如何設定使用目標,而不是自我?

+3

使用[自我類],而不是自我。你混淆了類方法和實例方法。 –

+0

不,navigationbarbutton項目是導航欄的即時對象,您只能將即時方法與它關聯。 – Saad

回答

1

請更改爲以下代碼:
這裏target應該是self而不是[self class]

[[UIBarButtonItem alloc] initWithTitle:@"title" 
           style:UIBarButtonItemStylePlain 
           target:self 
           action:@selector(method)]; 
+0

謝謝! [自學]完全工作! –

+0

歡迎您,如果有幫助,請不要忘記upvote和/或接受答案:) –

0

是的,你必須使用一個實例方法。只需從你的方法調用你的類方法。

1

是的,你可以通過

[[UIBarButtonItem alloc] initWithTitle:@"title" style:UIBarButtonItemStylePlain target: self 
    action:@selector(method)]; 

- (void)method 
{ 
    // here call class method 

    [YourClassName methodName]; 
} 
相關問題