0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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]];

2 Comments

I have ran your code. It should be selector[3] not *selector[3], but thanks!
Oops, good catch. That's what I get for copy-past-editing without testing it. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.