Saturday, April 7, 2012

CCCallFuncND Does Not Retain Data

I ran into a problem with cocos2d's CCCallFuncND function.  I originally wanted to use the schedule function to call a function in the future, however the schedule function does not accept parameters.  CCCallFuncND does accept parameters and to call it in the future, you can do the following to call someFunction with parameter param in 5 seconds:


        id actionDelay = [CCDelayTime actionWithDuration:5];
        id actionDone = [CCCallFuncND actionWithTarget:self selector:@selector(someFunction:data:) data:param];
        [self runAction:[CCSequence actions:actionDelay, actionDone, nil]];

I originally ran this code and got a EXC_BAD_ACCESS error.  This is because CCCallFuncND does not retain your objective C object.  To resolve this you'lll need to retain param and release it in your someFunction like so:

        id actionDelay = [CCDelayTime actionWithDuration:5];
        id actionDone = [CCCallFuncND actionWithTarget:self selector:@selector(someFunction:data:) data:[param retain]];
        [self runAction:[CCSequence actions:actionDelay, actionDone, nil]];


-(void)someFunction:(id)sender data:(void *)data {
  NSString* str = (NSString*) data;
  [str release];
}


This code works fine except that if for any reason your scene deallocates before someFunction gets called you have a memory leak.  For this reason, I won't be using CCCallFuncND in my code and will try to find another work around.


There is a discussion here about this:
http://cocos2d-central.com/topic/713-help-with-arc-and-cccallfuncnd/

No comments:

Post a Comment