【发布时间】:2010-12-11 17:15:26
【问题描述】:
我不确定这是否可行,但在 ruby 中,您可以使用 send 动态调用方法
例如如果我想为对象 foo 调用 bar 方法,我可以使用
foo.send("bar")
有没有什么方法可以使用objective-c做类似的事情?
tks!
【问题讨论】:
标签: iphone objective-c ruby
我不确定这是否可行,但在 ruby 中,您可以使用 send 动态调用方法
例如如果我想为对象 foo 调用 bar 方法,我可以使用
foo.send("bar")
有没有什么方法可以使用objective-c做类似的事情?
tks!
【问题讨论】:
标签: iphone objective-c ruby
if ([foo respondsToSelector:@selector(bar)])
[foo performSelector:@selector(bar))];
【讨论】:
据我所知,有几种选择
performSelector: 方法。但是,这仅适用于很少或没有参数的方法。objc_msgSend(),但直接调用它可能是个坏主意,因为运行时可能会在幕后执行其他操作。【讨论】:
performSelector:、performSelector:withObject: 和 performSelector:withObject:withObject: -- 超过 2 个参数,它不再是一个可行的选择。我认为 NextSTEP 曾经有一个 performv: 允许变量 args 或类似的东西,但我不太确定......
对于一般用途(带有返回值和任意数量参数的方法),使用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.
}
【讨论】: