Dair
Dair

Reputation: 16240

Function pointer problem in Objective-C

So I am trying to store a series of methods in an array (if that made sense).

void *pointer[3];
pointer[0] = &[self rotate];
pointer[1] = &[self move];
pointer[2] = &[self attack];
//...

What I am trying to do is have an array of stuff and based on the type of the object in the array, a certain method is invoked. And instead of having a bunch of if statement saying something like:

if ([[myArray objectAtIndex:0] type] == robot]) {
     //Do what robots do...
}
else if (...) {
}
else {
}

And having this in a timer I was hoping to make it something like this:

pointer[[[myArray objectAtIndex:0] type]]; //This should invoke the appropriate method stored in the pointer.

Right now the code above says (the very first block of code):

Lvalue required as unary '&' operand.

If you need any clarification just ask.

Also, just to let you know all the method I am calling are type void and don't have any parameters.

Upvotes: 0

Views: 624

Answers (2)

Jonah
Jonah

Reputation: 17958

Use function pointers if you need to pass around references to C functions but when working with methods on Objective-C objects you should really use selectors and the SEL type.

Your code would then be something like:

SEL selectors[3];
selectors[0] = @selector(rotate);
selectors[1] = @selector(move);
selectors[2] = @selector(attack);

...

[self performSelector:selectors[n]];

Upvotes: 3

puzzle
puzzle

Reputation: 6131

You can't just make a function pointer out of an Objective-C function using the & Operator.

You'll want to look into:

Any of these can do what you want. Definitely read about selectors (the @selector compiler directive and the SEL type) if you're unfamiliar with that (it's a basic concept that you'll need a lot). Blocks are fairly new (available since Mac OS X 10.6 and iOS 4) and they'll save you a ton of work where you would have needed target/selector, NSInvocation or callback functions on earlier versions of Mac OS X and iOS.

Upvotes: 5

Related Questions