Objective c performSelector:方法出现无法识别的选择器错误
我打电话Objective c performSelector:方法出现无法识别的选择器错误,objective-c,selector,unrecognized-selector,performselector,Objective C,Selector,Unrecognized Selector,Performselector,我打电话 [委托添加文本:button.titleLabel.text with selector:@selector(addElement:)fromKeyboard:self.name] 对应于 - (void)addText:(NSString *)text withSelector:(SEL)selectorName fromKeyboard:(NSString *)name { [tempData performSelector:@selector(selectorName)
[委托添加文本:button.titleLabel.text with selector:@selector(addElement:)fromKeyboard:self.name]
对应于
- (void)addText:(NSString *)text withSelector:(SEL)selectorName fromKeyboard:(NSString *)name {
[tempData performSelector:@selector(selectorName) withObject:text];
}
但是,当我对tempData调用performselector方法时,我得到了错误。当我用(addElement:)替换selectorName时,它工作正常。@selector(selectorName)
你忘了:
@选择器(selectorName:)你只能这样写
[tempData performSelector:selectorName withObject:text];
它已经是一个选择器,因此您不需要编写@selector(…)这里的
@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:
确保接收器响应选择器可能是个好主意,但不幸的是,它不起作用。我尝试了addElement/selectorName、addElement:/selectorName:、addElement:/selectorName和addElement/selectorName:@divol,这可能不是OP的问题,但对我的情况有所帮助。