Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 554
eriaac Avatar asked Feb 06 '09 08:02

eriaac


People also ask

How the function can be defined in Objective-C?

A function is a group of statements that together perform a task. Every Objective-C program has one C function, which is main(), and all of the most trivial programs can define additional functions. You can divide up your code into separate functions.

Can I use C in Objective-C?

You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.


1 Answers

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.

like image 164
Alex Wayne Avatar answered Sep 18 '22 06:09

Alex Wayne