Tuesday, January 11, 2011

Passing a parameter with Selector in Cocos2D or Box2D

Hope you know how to pass the parameter in selector in normal iPhone App. If you don't know it no problem, I am reminding it here once again.

[self performSelectorInBackground:@selector(startParsing)
 withObject:OBJECTNAME];

Here the object you are passing is OBJECTNAME.

In Cocos2D  or Box2D framework you have similar type of interface/class to call a function by selector. The interfaces are-
- CallFunc
- CallFuncN
- CallFuncND

I will not describe these all as the topic is not this. I will say what you will have to do in order to pass the parameter from a selector function.

You will have to use CallFuncND.
Suppose you want to pass an Array named myArray

If you can see CallFuncND has a init function like these one below...

-(id) initWithTarget : (id)t selector : (SEL)s 
data : (void*)d;

Here you will have to pass data as a parameter. You can see that it's data type is void pointer. So you have to pass the object as a void pointer parameter. Don't worry about passing Array. We will solve it here. Just pass the object in data.

Suppose your array is array.

Then init your CallFuncND as below...

[CallFuncND initWithTarget : self 
selector : @selector(myTest : data:) data : array ];

array is passing as a void pointer.
Now create your selector callback function as

-(void)myTest : (id) sender data:(void*)myData{
NSMutableArray *myArray=(NSMutableArray*)myData;
} 

Here you have to type caste the void pointer array to NSMutableArray. You have successfully passed the pointer of the object whether is void or anything it does not matter. If you what the object really is then you may type cast it into anything. Then you may use that object as you desired. Here I have shown it with an array. It can be done for any object as well.

No comments:

Post a Comment