2014-04-02 87 views
0

我正在制作一款游戏,而部分游戏则是一只收集鸡蛋的兔子。当兔子与蛋相撞时,我遇到了一个问题,那就是游戏崩溃。我得到的错误是收集< __NSArrayM:0x17805eed0>被列举时发生了变异。'碰撞后删除对象

我有一个鸡蛋的图像,鸡蛋出现在每两秒钟后,当兔子相交的鸡蛋时,我只想让鸡蛋消失并给予1分。

这里是我使用

在头文件中的代码,我有

@property (strong, nonatomic) NSMutableArray *eggs; 

和实现文件我有这个添加鸡蛋

UIImageView *egg = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth([[self gameView] frame]), holeBottom - 115 , 50, 60)]; 

[egg setImage:[UIImage imageNamed:@"easterEgg.png"]]; 
[[self gameView] insertSubview:egg belowSubview:[self counterLabel]]; 
[[self eggs] addObject:egg]; 

而这个检测碰撞并试图移除鸡蛋

for (UIView *egg in [self eggs]) { 
    [egg setFrame:CGRectOffset([egg frame], [link duration]*FBSidewaysVelocity, 0)]; 
    if (CGRectIntersectsRect (rabbit.frame, CGRectInset ([egg frame], 8, 8))) { 
     [[self eggs]removeLastObject]; 
     [self incrementCount]; 
    } 
} 

我希望你能看到我的代码出错了,并帮助我纠正这个问题。

预先感谢您的宝贵时间

回答

1

错误消息),而(例如,使用for in环)

的项目EATCHIP枚举它ST的解决办法是复制的收集和枚举复制一个

for (UIView *egg in [[self eggs] copy]) { // <-- copy 
    // you can modify `[self eggs]` here 
} 

NSMutableArray *tobeRemoved = [NSMutableArray array]; 
for (UIView *egg in [self eggs]) { 
    if (condition) 
     [tobeRemoved addObject:egg]; 
} 

[[self eggs] removeObjectsInArray:tobeRemoved]; 
+0

你是最棒的! @Bryan Chen非常感谢你的配偶,它的工作非常完美。 – user2632573

1

Collection <__NSArrayM: 0x17805eed0> was mutated while being enumerated正因为你遍历数组,而在同一时间删除该数组中的对象引起的。有几种方法可以解决这个问题,一种方法是在循环遍历原始数组eggs并在循环结束之后创建一个要删除的对象的新数组,循环遍历此新数组并执行删除操作。

代码示例:

NSMutableArray *eggs;//this is full of delicious eggs 

//... 

NSMutableArray *badEggs = [NSMutableArray array];//eggs that you want to removed will go in here 

for(NSObject *egg in [self eggs]){ 
    if([egg shouldBeRemoved]){//some logic here 
     [badEggs addObject:egg];//add the egg to be removed 
    } 
} 


//now we have the eggs to be removed... 

for(NSObject *badEggs in [self badEggs]){ 
    [eggs removeObject:badEgg];//do the actual removal... 
} 

:你的代码[[self eggs]removeLastObject];线看起来像一个错误在任何情况下......这将删除对象的数组的末尾(我不认为你如果很清楚,你不能可变集合(例如,删除元素要做到这一点...)