集合< __ NSArrayM:0x76c11b0>被枚举时发生突变 [英] Collection <__NSArrayM: 0x76c11b0> was mutated while being enumerated

查看:76
本文介绍了集合< __ NSArrayM:0x76c11b0>被枚举时发生突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是obj-c的新手,所以我必须缺少一些东西,但是当敌人碰到墙壁时,我的程序崩溃了。我已经找到了我从循环中移除敌人,而在循环中,但对于我的生活,我不知道如何解决它。
我的代码如下:

I'm relatively new to obj-c, so I must be missing something, but my program crash when an enemy collides with a wall. I've located where I'm removing the enemy from the loop, while in the loop, but for the life of me, i can't figure out how to fix it. My code is as follows:

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

(the error is "[allEnemies removeObject:enemyType1];")

// ALWAYS RUNNING
- (void)update:(ccTime)dt
{

//ALWAYS RUNNING -(void) update:(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


推荐答案

好吧,正如错误状态,你在数组被枚举时改变了数组。最简单的解决办法是对 code> for(CCSprite * enemyType1在[[allEnemies copy] autorelease])这种方式你枚举数组的副本元素,只是给你另一个容器来枚举它们),并且仍然可以修改可变数组。

Well, just as the error states, you mutated the array while it was being enumerated. The easiest fix is to do for (CCSprite *enemyType1 in [[allEnemies copy] autorelease]) This way you're enumerating a copy of the array (this does NOT copy the elements, just gives you another container to enumerate them in), and can still modify the mutable array.

枚举它们时不能修改容器。

You can not modify containers while enumerating them.

这篇关于集合&lt; __ NSArrayM:0x76c11b0&gt;被枚举时发生突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆