views:

17

answers:

2

Hi, I am totally new to cocos2d and Objective C. I just started studying the HelloWorld example that came with cocos2d package, and just couldn't figure out where in the application the -init() function within HelloWorldScene.m is getting called.

Here is the tutorial that I was following: http://www.bit-101.com/blog/?p=2123

Thanks in advance!

A: 

The init() method is being overridden in the scene. It is getting called within the base class when an instance of the scene is created. By overriding it, you get the opportunity to fire your own code.

jtalarico
+1  A: 

jtalarico is correct. I'd like to expand on his answer a bit.

In general, some form of [init] is called by convention whenever an object gets instantiated. For many objects, [init] is all that is needed, but some objects have more complex forms, such as [initWithSomething].

In Cocos2d, the init function is generally called by the [node] method, which is often used to construct an object in Cocos2d. For example, look in CCNode.m, and you will see this code:

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

Other objects have other constructors, but this is the main example.

So, if you subclass CCNode, you can override the [init] method and do your own stuff when an object gets created. Just be sure to call [super init] so that CCNode can do its own initialization, too.

cc
cc, thanks for your answer! This explains everything.
pwang