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

eriaac picture eriaac · Feb 6, 2009 · Viewed 14.7k times · Source

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 Objective C or is that too much to hope for?

Answer

Alex Wayne picture Alex Wayne · Feb 6, 2009

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.