Reputation: 57
I should really know this by now but I just can´t decide when to allocate game objects when when I don´t need to.
Example: I have a pause button in my game. This button is not allocated in any way, I put in my input layer like this:
pauseButton = [CCSprite spriteWithSpriteFrameName:@"pause.png"];
I´ve also done this with some labels.
However, I added my character object to the game with some help from a tutorial, like this:
[[[self alloc]initWithImage] autorelease];
(This line is a part of method)
Well, how do one decide if to allocate a game object or not? Is there a good practice or should I just allocate->autorelease everything I add to the game?
Upvotes: 1
Views: 80
Reputation: 435
Actually the 2 lines are essentially identical. spriteWithSpriteFrameName
is a static function of the CCSprite class. It returns an autorelease object.
initWithImage
is non-static so you need allocate it first, but since it's also marked autorelease, it behaves in the same way.
My rule of thumb is if there are static functions available that return auto-release objects, I use them for convenience sake. If you remove the autorelease from the second example, you will have to manually call "release" on the object to destroy it. You cannot call release on an autorelease object, so there may be cases where you want to destroy the object early (and not on scene change for instance).
Hope that helps!
Upvotes: 1