0

我打電話無法識別選擇錯誤與performSelector:方法

[delegate addText:button.titleLabel.text withSelector:@selector(addElement:) fromKeyboard:self.name]

相當於

- (void)addText:(NSString *)text withSelector:(SEL)selectorName fromKeyboard:(NSString *)name { 

    [tempData performSelector:@selector(selectorName) withObject:text]; 

} 

然而,當我打電話的執行選擇方法上的TempData,我得到的錯誤。當我用(addElement :)替換selectorName時,它工作正常。

回答

4

你只寫這樣的

[tempData performSelector:selectorName withObject:text]; 

它已經是一個選擇,所以你不需要寫@selectr( ...)

+0

它的工作原理,謝謝 – Mahir 2012-07-22 11:24:54

3

@selector(selectorName) 你忘記: @selector(selectorName :)

+0

不幸的是無法正常工作。我嘗試過addElement/selectorName,addElement:/ selectorName :, addElement:/ selectorName和addElement/selectorName: – Mahir 2012-07-22 11:23:03

+0

@divol,也許不是OP的問題,但它對我的情況有所幫助。 – terphi 2013-06-06 18:11:51

1

似乎有一點混亂圍繞@selector()結構在這裏:

@selector(selectorName)是一個字面值,用於選擇器內部大括號內的名稱, selectorName在這種情況下(非常類似於"selectorName"是引號內的C字符串的文字。這意味着您正嘗試將名爲selectorName的選擇器發送到tempData對象,該對象失敗。

如果你想選擇通過名字來發送,使用NSSelectorFromString()功能:

- (void)addText:(NSString *)text withSelector:(NSString *)selectorName fromKeyboard:(NSString *)name { 
[tempData performSelector:NSSelectorFromString(selectorName) withObject:text]; 
} 

這可能是一個好主意,以確保接收器響應在這種情況下,選擇使用-respondsToSelector:

相關問題