Hello!
I’m new to cocos2dx, and I’ve been in trouble with a memory problem.
I’m using Xcode to develop my game.And here is a part of my code:
bool MainMenuScene::init() {
if (!Scene::init()) return false;
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("res/HisotenSoku/bgm/op2.mp3", true);
this->view = MainMenuViewLayer::create();
this->opening = MainMenuOpeningLayer::create();
this->ui = MainMenuUILayer::create();
this->addChild(this->view);
this->addChild(this->opening);
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [&](Touch* touch, Event* event) {
if (this->hasEntered) {
// ...
} else {
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playEffect("res/HisotenSoku/se/061.wav");
this->addChild(this->ui);
this->removeChild(this->opening);
this->hasEntered = true;
}
return true;
};
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
In MainMenuOpeningLayer, I’ve added some Sprites and Actions to display something like staff list and other information.What I need is when the player touches screen he can skip the display but do not remove the Sprites in MainMenuViewLayer.When I debugged the program, it showed “reference count should be greater than 0” at Ref::retain().
The wrong place is
this->addChild(this->ui);
in lambda expression.
Thus I think it is a memory problem and I tried this:
bool MainMenuScene::init() {
if (!Scene::init()) return false;
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playBackgroundMusic("res/HisotenSoku/bgm/op2.mp3", true);
this->opening = MainMenuOpeningLayer::create();
this->addChild(MainMenuViewLayer::create());
this->addChild(this->opening);
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [&](Touch* touch, Event* event) {
if (this->hasEntered) {
// ...
} else {
auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->playEffect("res/HisotenSoku/se/061.wav");
this->addChild(MainMenuUILayer::create());
this->removeChild(this->opening);
this->hasEntered = true;
}
return true;
};
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
This time it works as I expected.
So why the former will be crashed?Is it just because I didn’t use the Layer immediately after created and it was deleted by cocos2dx?
If so, how can I save a Node object from being deleted?
Thanks a lot. 
Thanks