is there an objective-c "equivalent" to ruby's send method?
I'm not sure this is possible, but in ruby, you can dynamically call a method using send
e.g. if I want to invoke the bar method for the object, foo,开发者_StackOverflow社区 I can use
foo.send("bar")
Is there any way of doing something similar using objective-c?
tks!
There are several options, as far as I know
- You could use NSObject's
performSelector:
method. This, however, is only really good for methods that have few or no arguments. - Use the NSInvocation class. This is a bit heftier, but is a lot more flexible.
- You might be able to use
objc_msgSend()
, but it's probably a bad idea to call it directly, due to other stuff that the runtime might be doing behind the scenes.
For general use (method with a 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.
}
if ([foo respondsToSelector:@selector(bar)])
[foo performSelector:@selector(bar))];
精彩评论