收集<__ NSArrayM:0x76c11b0>在枚举时发生了变异

use*_*516 7 objective-c cocos2d-iphone

我对obj-c比较新,所以我必须遗漏一些东西,但是当敌人与墙碰撞时我的程序会崩溃.我已经找到了我从循环中移除敌人的地方,而在循环中,但对于我的生活,我无法弄清楚如何解决它.我的代码如下:

(错误是"[allEnemies removeObject:enemyType1];")

//始终运行 - (无效)更新:(ccTime)dt {

for (CCSprite *enemyType1 in allEnemies) { //for every attacking unit in allEnemies

    //Adjust the collison box for each enemey depending on the height of the enemy
    float a;
    float b;
    float yOne = (wall.contentSize.height-enemyType1.position.y);
    float yTwo = (wall.contentSize.height);
    float xTwo = 30;
    a = (xTwo*(yOne/yTwo)); // always < 1
    b = xTwo-a;             // always > 1


    //Create the altered collison box 
    CGRect enemyType1Rect = CGRectMake (
                enemyType1.position.x - (enemyType1.contentSize.width/2), 
                enemyType1.position.y - (enemyType1.contentSize.height/2), 
                enemyType1.contentSize.width+b, 
                enemyType1.contentSize.height
                                       );


    //If the enemey hits the wall, stop it, then add it to the attacking enemies array
    if (CGRectIntersectsRect(enemyType1Rect, wall.boundingBox)) {
        [enemyType1 stopAllActions];
        [allEnemies removeObject:enemyType1];
        [attackingEnemies addObject:enemyType1];            
    }


}
//Wall Collison END
Run Code Online (Sandbox Code Playgroud)

Jos*_*erg 24

好吧,正如错误所述,你在枚举时改变了数组.最简单的解决方法就是这样做for (CCSprite *enemyType1 in [[allEnemies copy] autorelease])你要枚举数组的副本(这不会复制元素,只是给你另一个容器来枚举它们),并且仍然可以修改可变数组.

枚举它们时无法修改容器.

  • @ LearnCocos2D这是因为这样做[阵列reverseEnumerator]给你另一个枚举傻冒处理,本质上是不同的阵列. (2认同)