What is the difference between
CCNode *hero= [[CCNode alloc] init]; vs CCNode *hero= [CCNode node];
Which method is more preferable and why?
What is the difference between initialization CCNode?
(5 posts) (4 voices)-
Posted 2 years ago #
-
Please correct me if I'm wrong.
CCNode *hero [[CCNode alloc] init]; //you create an object of hero and you also call the constructor of init method.
CCNode *hero =[CCNode alloc]; //you create an object of hero without initialize Or call the constructor of init method.
I prefer to use the second statement if I don't want to initialize my variables inside the constructor.
Posted 2 years ago # -
I think [CCNode node] is just a convenient short-hand method to call. However, there is a slight difference between the two methods you posted.
Here's the method definition from CCNode.m
+(id) node { return [[[self alloc] init] autorelease]; }As you probably noticed, the difference is the 'autorelease'.
- kalx
Posted 2 years ago # -
Ahh my mistake. I thought the second statement same as the first one with the keyword: 'alloc'. I was blind. Sorry.
Posted 2 years ago # -
Anytime you see one of these class-level "convenience methods" in Obj C, it's gonna return an autoreleased object... Which basically just means that you've gotta retain it manually if you want it to stick around. In Coco2D you're usually adding a node as a child of another node when you're creating it, so you won't need to explicitly retain it or release it. This is fine:
CCNode *hero = [CCNode node]; [self addChild:hero];In this situation,
self(which in this case would have to be a CCNode) is now retaining hero in it's children array. That's the only place it's retained. If it's removed from the display list later([self removeChild:hero];), it'll be dealloced.On the other hand, if you use alloc+init, it'll look like this:
CCNode *hero = [[CCNode alloc] init]; [self addChild:hero];This is not necessarily wrong, but it means you've gotta be in charge of releasing it. If you remove it from the display list(
[self removeChild:hero];), it'll still be retained, and you'll have a memory leak unless you release it. To solve this you'll usually have an instance variable to refer to it, and then you'll release it in your dealloc:-(void)dealloc { [hero release]; [super dealloc]; }Posted 2 years ago #
Reply
You must log in to post.