【问题标题】:Objective C substite method trigger name with string带有字符串的Objective C替换方法触发器名称
【发布时间】:2014-07-23 06:04:52
【问题描述】:

我有一个数组,其中包含一个函数的名称和一个看起来像这样的参数。

(
    [0] => (
        [0] => @"getName"
        [1] => @"This is the name"
    )
)

对于我的方法,它看起来像这样。

-(NSString *)getName:(NSString *)name {...}

我知道触发一个我必须做的方法[[AppDelegate alloc] getName:string];,但是有什么方法可以用array[0][0] 替换getName,用array[0][1] 替换string

【问题讨论】:

  • 你想用字符串代替函数还是对象?你说“函数”,然后你说你想用字符串替换AppDelegate
  • 糟糕。我的错。我想将getName 替换为array[0][0],将string 替换为array [0][1]。编辑问题以修复
  • 这是否适用于您无法事先知道函数名称的情况?还是您已经知道所有可能的功能?

标签: ios objective-c arrays methods


【解决方案1】:

由于您需要传入参数并获取返回值,请使用 NSInvocation。 更多细节在这里NSInvocation for Dummies?

对于NSInvocation的set Selector,可以设置选择器为NSSelectorFromString(array[0][0]); 参数和返回值也是如此。

【讨论】:

    【解决方案2】:

    你在这里做的有点危险。无论如何,您可以通过使用选择器来实现这一点。

    对象采用一种协议,告诉它们是否可以执行某些操作。所以基本上,你必须首先从数组中获取函数的字符串和参数。

    然后使用允许在运行时调用它的函数创建一个选择器。

    SEL aSelector = NSSelectorFromString(@"methodName");
    

    然后,询问您的对象是否可以执行选择器(如果您只是盲目地发送它可能会发生坏事)

    - (BOOL)respondsToSelector:(SEL)aSelector
    

    最后,您可以使用之前获得的对象(这是参数)执行选择器。

    - (id)performSelector:(SEL)aSelector withObject:(id)anObject
    

    选择器见此:https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html

    这对于对象协议: https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/respondsToSelector:

    编辑:正如 danh 所提到的,选择器名称后面有一个冒号很重要,因为您的方法接受一个参数。如果没有传递参数,你就不需要它。

    自从

    - (id)doSomething;
    

    不同于

    - (id)doSomething:(id)argument;
    

    【讨论】:

      【解决方案3】:

      这是@Chiquis 想法的一个工作示例。 (请注意,您的选择器需要一个尾随冒号):

      -(void)doSomethingALittleDangerous
          NSArray *array = @[@[@"getName", @"this is the name"]];
      
          NSString *notQuiteTheSelectorStr = array[0][0];
          NSString *selectorStr = [notQuiteTheSelectorStr stringByAppendingString:@":"];
      
          SEL selector = NSSelectorFromString(selectorStr);
      
          // this generates a warning because the compiler cannot confirm that
          // self implements this programmatically derived selector
          if ([self respondsToSelector:selector]) {
              NSString *name = [self performSelector:selector withObject:array];
          }
          NSLog(@"%@", name);
      }
      
      - (NSString *)getName:(NSArray *)array {
          return array[0][1];
      }
      

      【讨论】:

      • 是的,忘记了,没有冒号是另一种方法。
      • 谢谢!这正是我一直在寻找的。我正在探索@Chiquis 的想法,但由于我是 obj-c 的新手,所以我无法自己获得工作版本。太棒了。谢谢! :)
      • 您不会碰巧知道忽略该警告的标志吗?我知道如果我要禁用有关未使用参数的警告,例如我会使用-Wno-unused-parameter
      猜你喜欢
      • 2011-07-28
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多