【问题标题】:is there an objective-c "equivalent" to ruby's send method?ruby 的 send 方法是否有objective-c“等效”?
【发布时间】:2010-12-11 17:15:26
【问题描述】:

我不确定这是否可行,但在 ruby​​ 中,您可以使用 send 动态调用方法

例如如果我想为对象 foo 调用 bar 方法,我可以使用

foo.send("bar")

有没有什么方法可以使用objective-c做类似的事情?

tks!

【问题讨论】:

    标签: iphone objective-c ruby


    【解决方案1】:
    if ([foo respondsToSelector:@selector(bar)])
        [foo performSelector:@selector(bar))];
    

    【讨论】:

      【解决方案2】:

      据我所知,有几种选择

      1. 你可以使用 NSObject 的performSelector: 方法。但是,这仅适用于很少或没有参数的方法。
      2. 使用NSInvocation 类。这有点重,但更灵活。
      3. 您也许可以使用 objc_msgSend(),但直接调用它可能是个坏主意,因为运行时可能会在幕后执行其他操作。

      【讨论】:

      • 对,只有 performSelector:performSelector:withObject:performSelector:withObject:withObject: -- 超过 2 个参数,它不再是一个可行的选择。我认为 NextSTEP 曾经有一个 performv: 允许变量 args 或类似的东西,但我不太确定......
      • 当您使用 NSInvocation 或切换到使用字典作为参数时,会出现两个以上的参数。没那么难,只是多打几个电话而已。
      • 另外,1.也只有当参数类型都是对象并且返回类型是对象或void时也是好的
      【解决方案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.
      }
      

      【讨论】:

        猜你喜欢
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        相关资源
        最近更新 更多