操作后释放新对象

时间:2016-09-27 03:57:08

标签: c++ cocos2d-x release retain

在我的游戏场景中,我从一个随着MoveBy动作随机移动的球类产生球。我的问题是,在MoveTo动作结束后如何释放球?请参阅下面的代码:

//GameScene class
 ...

 Ball *ball = new Ball(); //<----need to release this after action is over
 ball->spawnBall(this); 

 ...


//Ball class
 ...

void Ball::spawnBall(cocos2d::Layer *layer){

ball = Sprite::create();
layer->addChild(ball);
auto action = Sequence::create(MoveBy::create(...)), RemoveSelf::create(),   null);
ball->runAction(action);

}

我想控制它的内存(堆),因为我发现使用了自动发布(堆栈):

  Ball ball;
  ball.spawnBall(this);

有些球会随机停止。我想他们在产生时会覆盖每个人的记忆。

由于

1 个答案:

答案 0 :(得分:0)

如果runAction是异步调用,那么你的问题似乎是你的堆栈变量超出了范围:

int GameScene::func()
{
 Ball ball;
 ball.spawnBall(this); 
 return 0; //ball is automatically deleted here
}

你应该能够

int GameScene::func()
{
 Ball *ball = Ball::create(); //dont use new here, use create() function here and autorelease
 ball.spawnBall(this); 
 //autorelease here
 return 0;
}

我强烈建议您阅读Memory deallocation in Cocos2d-x