Domanda

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;
    }
} 
È stato utile?

Soluzione

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.

Altri suggerimenti

Thanks for your reply, but I met another question:

void TextureCacheTestScene::runThisTest()
{

    CCLayer* pLayer = new TextureCacheTest(); // not add the reference for pLayer
    addChild(pLayer); // add 1

    CCDirector::sharedDirector()->replaceScene(this);
    pLayer->release(); // delete 1
}

Why we need to call release() after the replaceScene()? I just find the replaceScene add the reference for the scene not the layer, so I feel confused with what happened:

  1. addChild(pLayer) // add reference for the pLayer;
  2. relplaceScene() // add reference for the scene;(don't add referen for the pLayer)
  3. pLayer->release() // delete reference for the pLayer; So why the pLayer is not be recycled? I don't think if the scene is alive then the pLayer can not be recycled, I believe the reference account will not care that.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top