Dynamic call of the Objective-C method

How can I name a selector with its name in NSString * in object c? I also need to call the selector only if the target accepts it. eg.

 +(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 does not implement it, nothing should happen.

+6
source share
2 answers
 SEL selector = NSSelectorFromString(method); if ([object respondsToSelector:selector]) { [object performSelector:selector]; } 
+15
source

First you use the NSSelectorFromString() method to convert the string to the method name, for example:

SEL methodToCall = NSSelectorFromString(stringToConvertToMethod);

Then you test 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 drawback is that you cannot pass arguments. To pass an argument, you call the NSObject performSelector:withObject: method. To pass two arguments, performSelector:withObject:withObject:

+6
source

Source: https://habr.com/ru/post/890265/


All Articles