Remove CCNode from parent after a sequence of actions

P.S:
Well, P here stands for Pre instead of Post, I guess. The following cocos2d discussion was started 3 years ago. Now I realize that there is a method: [CCNode removeFromParent]

So a useful post from cocos2d forum: http://www.cocos2d-iphone.org/forum/topic/981



I have some sprites and labels on the Layer. Before removing them they must do some actions (fade out for example). But after that I need to remove them from the layer with using [self removeChild:child cleanup:YES]. For that I create classes AutoCleaningSprite and AutoCleaningLabel which inherit Sprite and Label class and have new method:
- (void) removeFromParent{
CocosNode *parent=self.parent;
[parent removeChild:self cleanup:YES];
}
So for removing this objects after animation I used next actions:
[someAutoCleaningSprite runAction:
[Sequence actions:[FadeOut actionWithDuration:0.5],
[CallFunc actionWithTarget:someAutoCleaningSprite selector:@selector(removeFromParent)],nil]];
Is it correct method? Or may be there is something more simple way for removing CocosNode objects from the parent Object?
And I have another question - is it need to invoke [sprite release]; after [self removeChild:sprite cleanup:YES];?
Thanks..
Answer:


re:
(void) removeFromParent{
CocosNode *parent=self.parent;
[parent removeChild:self cleanup:YES];
}
This strategy will work and I've found it very useful on my projects but one thing anyone who tries it needs to be aware of is a really really really evil memory bug that gets caused unless your careful. First off, the solution:
CocosNode *parent=self.parent;
[self retain];
[parent removeChild:self cleanup:YES];
[self autorelease];
Huge hack I know, and there are cleaner ways to do this but what happens if you don't is total heisenbuggery. Background:
- The NSInvocation object associated with the CallFunc action wants to write a 'return value' to an address in the NSInvocation object ... even if your function doesn't return anything.
- When you call removeChild:self cleanup:YES your sprites ref count goes down by one
- If your sprites ref count just hit zero (as it probably will), instead of being released 'at some time in the future' its going to get deallocated NOW. Thank apple for that little bit of magic they do when removing objects from NSArrays
- That deallocation cascades to the Action and then the NSInvocation all before your function returns.
If you've got anything else going on (other threads for instance that may be allocating something ... I'm looking at you OpenFeint) the NSInvocation return is about to write on some memory that no longer belongs to it ... and you will likely not find out about it until way past too late ;)

0 komentar:

Posting Komentar