Unrecognized selector error with performSelector: method
-
22-06-2021 - |
Question
I call
[delegate addText:button.titleLabel.text withSelector:@selector(addElement:) fromKeyboard:self.name]
which corresponds to
- (void)addText:(NSString *)text withSelector:(SEL)selectorName fromKeyboard:(NSString *)name {
[tempData performSelector:@selector(selectorName) withObject:text];
}
However, when I call the perform selector method on tempData, I get the error. When I replace selectorName with (addElement:) it works fine.
Solution
You only write like that
[tempData performSelector:selectorName withObject:text];
it is already a selector so you dont need to write @selectr(...)
OTHER TIPS
@selector(selectorName) you forget : @selector(selectorName:)
It seems there is a bit of confusion around the @selector()
construct here:
The @selector(selectorName)
is a literal for the selector with the name inside the braces,
selectorName
in this case (much like "selectorName"
is a literal for the C string inside the quotes. This means that you are trying to send selector named selectorName
to the tempData
object, which fails.
If you want to pass in the selector to send by name, use the NSSelectorFromString()
function:
- (void)addText:(NSString *)text withSelector:(NSString *)selectorName fromKeyboard:(NSString *)name {
[tempData performSelector:NSSelectorFromString(selectorName) withObject:text];
}
It might be a good idea to make sure the receiver responds to the selector in this case by using -respondsToSelector: