Dvole
Dvole

Reputation: 5795

Why strange declaration of CCLayer in cocos2d?

I have a class GameScene, during init of which I make a scene and attach a child to it - a layer. I noticed strange code for it:

    CCScene *scene = [CCScene node];
    CCLayer *layer = [GameScene node];
    [scene addChild:layer];

Why not do this instead?

CCLayer *layer = [CCLayer node];

This doesn't add to readability or am I missing something fundamental here? Also, why not use alloc init at all?

Upvotes: 0

Views: 255

Answers (1)

tallen11
tallen11

Reputation: 1377

[CCNode node];

is a static (class) method. It automatically calls [[[self alloc] init] autorelease];

Any CCNode subclass can be initialized using this static initializer. It is basically for convenience and is really not needed. (Although, like I said, it is nice to have).

Class methods use the "+" sign and instance methods use the "-" sign. Class methods are like static methods in Java. They can be called without creating an instance of that class. It could look like this: [YourClass doSomething]; //Doesn't need an instance of YourClass

Instance methods need an instance of their class to be able to be run. This would look like:

YourClass *yClass = [[YourClass alloc] init];
[yClass doSomethingElse]; //Needs an instance of YourClass

I haven't looked, but I assume the node method looks something like this:

+ (CCNode*)node {
    return [[[self alloc] init] autorelease];
}

The odd declaration just returns a scene (initialized with a static initializer) with your custom layer as a child, that the CCDirector can then use and display.

EDIT: something I feel would add clarity.

The strange declaration is just a static initializer + (CCScene*)scene which returns a scene.

Upvotes: 2

Related Questions