iphone - 由于从 NSMutableArray 中删除 CCSprite 等元素而导致崩溃

标签 iphone cocos2d-iphone nsmutablearray ccsprite removechild

所以,事情是这样的。

我目前正在开发 Cocos2d 游戏,其中有很多障碍。像这样每隔 10 秒就会在屏幕上添加一个障碍物。

ObstacleSprite* newObstacle = [ObstacleSprite spriteWithFile:@"Obstacle.png" rect:CGRectMake(0, 0, 20, 20)];
            newObstacle.position = ccp(mainPlayer1.position.x,10);
[self addChild:newObstacle];

[self.arrayForObstacles addObject:newObstacle];

现在,我将这些障碍物插入到 arrayForObstacles 中,因为我还想继续检查 Obstacles 和 MainPlayer 是否不会发生碰撞。

我是借助这个函数来检查的。

- (void) checkCollisionWithObstacle
{
    if(mainPlayer1.playerActive)
    {
        for(int  i = 0; i < [self.arrayForObstacles count]; i++)
        {
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:i];
            if(newObstacle != nil)
            {
                if(CGRectIntersectsRect([mainPlayer1 boundingBox], [newObstacle boundingBox]))
                {
                    mainPlayer1.livesLeft--;
                }
            }
        }
    }
}

问题

问题是当我达到一定分数时,其中一个障碍会被删除。清除障碍的工作方式与先进先出 (FIFO) 模式相同。因此,为了删除障碍,我编写了以下方法:

- (void) keepUpdatingScore
{
    //update new score
    mainPlayer1.score+=10;
    //remove obstacle when score increases by 5k
    if(mainPlayer1.score > 5000 && mainPlayer1.score > 0)
    {        
        mainPlayer1.playerActive = NO;

        if([self.arrayForObstacles count] > 0)
        {            
            CCLOG(@"count is %d",[self.arrayForObstacles count]);
            ObstacleSprite* newObstacle = [self.arrayForObstacles objectAtIndex:0];
            [self.arrayForObstacles removeObjectAtIndex:0];
            [self removeChild:newObstacle cleanup:YES];

            CCLOG(@"count is %d",[self.arrayForObstacles count]);
        }

        mainPlayer1.playerActive = YES;

    }    
    else
    {

    }

分数超过 5000 分时崩溃!

更新

当它再次转到checkCollisionWithObstacle方法时发生崩溃。

这是线程外观。

enter image description here

这是崩溃的那行。

enter image description here

最佳答案

您似乎使用 mainPlayer1.playerActive 作为信号量来阻止检查 keepUpdatingScore 方法中删除的 checkCollisionWithObstacle 循环(它们是异步的吗?)。假设它们是这样,如果代码在 checkCollisionWithObstacle 中开始循环后进入 keepUpdatingScore ,则阻止循环访问的方式将不起作用...您的里程将会有所不同。

关于iphone - 由于从 NSMutableArray 中删除 CCSprite 等元素而导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841691/

相关文章:

ios - 当我快速导入 OBJ-C 类时,Xcode 不会提示我添加 Bridging-header.h

objective-c - MobFox 总是给我回复 "No inventory for ad request"

ios - 从cocos2d应用播放iTunes歌曲预览

objective-c - (iOS) NSMutableArray 作为属性 addObject 什么都不做

ios - 在核心数据中存储和获取 NSMutableArray

iphone - 如何设置tableView的背景颜色

iphone - 什么是 NSZone?使用initWithZone :?有什么好处

iphone - 如何同时本地化 iPhone(monotouch) 和 Windows Phone 7 应用程序?

objective-c - 添加到图层后水平翻转 CCSprite

iphone - 使用 NSMutableArray 与 NSArray 的缺点?