ruby的send方法是否有客观的c“等价”?

时间:2009-10-30 18:47:08

标签: iphone objective-c ruby

我不确定这是否可行,但在ruby中,您可以使用send

动态调用方法

e.g。如果我想为对象 foo 调用 bar 方法,我可以使用

foo.send("bar")

有没有办法用objective-c做类似的事情?

TKS!

3 个答案:

答案 0 :(得分:13)

据我所知,有几种选择

  1. 您可以使用NSObject的performSelector:方法。但是,这只适用于参数很少或没有参数的方法。
  2. 使用NSInvocation课程。这有点过分了,但更灵活。
  3. 您可以使用objc_msgSend(),但由于运行时可能在幕后执行的其他操作,直接调用它可能是一个坏主意。

答案 1 :(得分:3)

对于一般用途(带有返回值和任意数量参数的方法),请使用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.
}

答案 2 :(得分:-1)

if ([foo respondsToSelector:@selector(bar)])
    [foo performSelector:@selector(bar))];
相关问题