Is it possible to pass a method as an argument in Objective-C?

后端 未结 3 2181
说谎
说谎 2020-12-25 13:05

I have a method that varies by a single method call inside, and I\'d like to pass the method/signature of the method that it varies by as an argument... is this possible in

3条回答
  •  盖世英雄少女心
    2020-12-25 13:38

    NSInvocation is a class for wrapping up a method calls in an object. You can set a selector (method signature), set arguments by index. You can then set a target and call invoke to trigger the call, or leave the target unset and use invokeWithTarget: in a loop of some sort to call this on many objects.

    I think it works a little like this:

    NSInvocation *inv = [[NSInvocation alloc] init];
    [inv setSelector:@selector(foo:bar:)];
    [inv setArgument:123 atIndex:0];
    [inv setArgument:456 atIndex:1];
    
    for (MyClass *myObj in myObjects) {
      [inv invokeWithTarget:myObj];
    }
    

    Or if you dont want to pass invocation objects into this method you can use the SEL type to accept a selector (method signature).

    -(void)fooWithMethod:(SEL)selector;
    

    Then assign the selector to an invocation object in order to call it on objects.

提交回复
热议问题