Search code examples
cocos2d-xretainaddchild

Cocos2d-X why call retain() before addChild()


Can anybody help me to find out why we need to call the retain() before the addChild(), I just thought if we call the addChild, the pool will manage the CCNode we added, so why we need to retain it and release it by ourself?

bool GameOverScene::init()
{

    if( CCScene::init() )
    {
        this->_layer = GameOverLayer::create();
        this->_layer->retain();
        this->addChild(_layer);

        return true;
    }
    else
    {
        return false;
    }
}

GameOverScene::~GameOverScene()
{

    if (_layer)
    {
        _layer->release();
        _layer = NULL;
    }
} 

Solution

  • I am not familiar with the memory management in Cocos2D-X, which is written in C++. However, if it is similar to the reference-counting memory management in Cocoa, then every time you set an instance variable, you should release the previous value and retain the new value.

    Sure, in this case, we happen to know that by adding it as a child to ourselves, it will also be retained there. However, it makes your code fragile by relying on something else to retain it. So every time you create an instance variable, you have to think about whether it may be retained by something else, and you have to remember this decision everywhere you use this variable. It is better to just consistently always retain instance variables. It never hurts to retain it more times.