CCLabelTTF going null

Hi,

`bool GameScene1::init()
{
isAdded = false;
label_new = CCLabelTTF::labelWithString(“This is my first screen!”,“Arial”,22);
this->setIsTouchEnabled(true);
CCLabelTTF* label = CCLabelTTF::labelWithString(“Demo Text”,“Arial”,22);
addChild(label);
return true;
}

CCScene* GameScene1::getScene()
{
GameScene1* secene = GameScene1::node();
CCScene* scene1 = new CCScene();
scene1->addChild(secene);
return scene1;
}

void GameScene1::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent)
{
if (isAdded)
{
removeChild(label_new, true);
isAdded = false;
return;
}

isAdded = true;
addChild(label_new);

}

bool GameScene1::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
return true;
}`

I have CCLabelTTF pointer variable declared in .h file.
I have initialized CCLabelTTF in init() method but in ccTouchesBegan it is going null.
Can anybody tell me why this is happening?

I’m not that well versed in cocos memory management, but I think that if you didn’t add your label_new as a Child to the scene it may have gotten destroyed. Try doing
label_new->retain() on it in the init() method.

Afaik, Pawel is correct and the easiest way to keep it in memory is to add it to the scene as a child as soon as it’s declared. Otherwise it will get released as soon as it leaves scope (the end of the function). This happens because it’s an autorelease object, and it tries to release from memory when there are no references to it (if you dont add it as a child or retain it, there are no references to it). The reason i suggest adding it as a child instead of retaining it is because it will automatically release as part of your scene’s destruction phase (no manually managing retain and release is nice!)