OGeek|极客世界-中国程序员成长平台

标题: ios - raywenderlich 教程 - 简单的 iphone 游戏 - 第 2 部分 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:57
标题: ios - raywenderlich 教程 - 简单的 iphone 游戏 - 第 2 部分

我正在使用 iphone games tutorial 的第二部分,我对 ccTouchesEnded 方法的实现感到困惑。这是实现“射击”的地方:玩家(一门大炮)转向接触的方向,射弹被射击。 我不清楚的部分是:_nextProjectile 似乎在它仍然可以使用时被释放(通过它下面的代码 - _nextProjectile runAction)。 您能否解释一下为什么此时释放该对象是安全的?

- (void)ccTouchesEndedNSSet *)touches withEventUIEvent *)event {

[_player runAction:

 [CCSequence actions:

  [CCRotateTo actionWithDuration:rotateDuration angle:cocosAngle],

  [CCCallBlock actionWithBlock:^{

     // OK to add now - rotation is finished!

     [self addChild:_nextProjectile];

     [_projectiles addObject:_nextProjectile];



     // Release

     [_nextProjectile release];

     _nextProjectile = nil;

 }],

  nil]];



// Move projectile to actual endpoint

[_nextProjectile runAction:

 [CCSequence actions:

  [CCMoveTo actionWithDuration:realMoveDuration position:realDest],

  [CCCallBlockN actionWithBlock:^(CCNode *node) {

     [_projectiles removeObject:node];

     [node removeFromParentAndCleanup:YES];

 }],

  nil]];



}



Best Answer-推荐答案


之前在 ccTouchesEnded:withEvent: 中,您在此行增加了 _nextProjectile 的保留计数:

_nextProjectile = [[CCSprite spriteWithFile"projectile2.png"] retain];

因此,稍后您必须减少保留计数以防止内存泄漏。换句话说:您有责任释放此保留。这就是这条线的来源:

[_nextProjectile release];

为什么在那个时候释放它是安全的?您在问题中发布的代码段实际上都是一系列操作中的操作。

[_player runAction:[CCSequence actions:...]];

对对象执行操作会增加该对象的保留计数。这意味着 Action 对象本身创建并持有另一个对 _nextProjectile 的引用。 Action 序列是在 Action 实际执行之前创建的,因此 Action 对象已经拥有自己对 _nextProjectile 的引用。所以在其中一个 Action 中释放它实际上是安全的。他们等待释放 _nextProjectile,直到这些行通过:

[self addChild:_nextProjectile];
[_projectiles addObject:_nextProjectile];

这些行之前的版本可能(我没有看过除了 ccTouchesEnded:withEvent: 之外的任何其他代码)会导致 EXC_BAD_ACCESS 运行时错误。

以下是有关保留计数的更多信息:cocos2d forum

关于ios - raywenderlich 教程 - 简单的 iphone 游戏 - 第 2 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17248005/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4