calling retain when creating a object

calling retain when creating a object
0.0 0



In cocos2d-X we can create objects by two methods

  1. Constrcutor
  2. Calling the create method

When do we need to call the retain function ? I hear we only need to do so via the static create method ?

Kind Regards


You shouldn’t create cocos objects with your bare hands through calling a constructor except if you doing something very special. Use factory (CCSprite::create(…)) instead. You need to manually call retain() only if you do not add this object on the scene and still you want it to stay alive. If it’s a regular sprite on a scene - just add it to parent and retain() will be automatically called. If you create a cocos object with factory method and don’t add it anywhere it will be destroyed after some time.
To get deeper you can just read the source codes and check out objC retain/release/autorelease mechanism.


A typical create func is like this:

MyLayer* pRet = new MyLayer(..);
    if (pRet && pRet->init(..)) {
        return pRet;
    } else {
        delete pRet;
        pRet = NULL;
        return NULL;

You don’t need to call retain via create method, and this is the recommended way to create a new object.
If you call constructors directly, you need to call init(…) and autorelease(). I suggest NEVER do it this way.