7

How can I call a selector with its name in NSString * in objective c? I also need to call the selector only if the target will accept it. e.g.

+(void) callMethod: (NSString *) method onObject: (id) object
{
    // do some magic
}

When I call callMethod: @"Foo" onObject: obj if obj implements Foo then [obj Foo] should be called, if it doesn't implement it, nothing should happen.

2 Answers 2

16
SEL selector = NSSelectorFromString(method);
if ([object respondsToSelector:selector]) {
    [object performSelector:selector];
}
Sign up to request clarification or add additional context in comments.

Comments

6

First, you use the NSSelectorFromString() method to convert the string into a method name, like so:

SEL methodToCall = NSSelectorFromString(stringToConvertToMethod);

Then, you check for the method on the receiver and call the method if it exists:

if ([receiver respondsToSelector:methodToCall]) {

  //  Method exists, call it.
  [receiver performSelector:methodToCall];

}

Just note that a potential downside is that you will not be able to pass in arguments. For passing an argument, you would call the NSObject method performSelector:withObject:. For passing two arguments, performSelector:withObject:withObject:.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.