Is there objective-c equivalent to the ruby ​​submission method?

I'm not sure if this is possible, but in ruby ​​you can dynamically call a method using send

eg. if I want to call the bar method on an object, foo , I can use

foo.send("bar") 

Is there a way to do something like this with objective-c?

Tks!

+4
source share
3 answers

There are several options, as far as I know

  • You can use the NSObject performSelector: method. This, however, is very useful for methods that have few or no arguments.
  • Use the NSInvocation class. It is a bit heavier, but much more flexible.
  • You might be able to use objc_msgSend() , but it is probably a bad idea to name it directly, due to other things that runtime can execute behind the scenes.
+13
source

For general use (method with return value and any number of arguments) use NSInvocation :

 if ([target respondsToSelector:theSelector]) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [target methodSignatureForSelector:theSelector]]; [invocation setTarget:target]; [invocation setSelector:theSelector]; // Note: Indexes 0 and 1 correspond to the implicit arguments self and _cmd, // which are set using setTarget and setSelector. [invocation setArgument:arg1 atIndex:2]; [invocation setArgument:arg2 atIndex:3]; [invocation setArgument:arg3 atIndex:4]; // ...and so on [invocation invoke]; [invocation getReturnValue:&retVal]; // Create a local variable to contain the return value. } 
+3
source
 if ([foo respondsToSelector:@selector(bar)]) [foo performSelector:@selector(bar))]; 
-one
source

All Articles