FBryant87
FBryant87

Reputation: 4615

iPhone game: enumerating over enemies

So I'm constantly checking collision detections and whenever an enemy gets killed I remove it from the array I'm iterating over.

This is giving me enmueration mutation exceptions, what is the normal way to solve this?

People talked about making copies of the array, but when I'm iterating over it every fraction of a second that idea seems ridiculous.

Upvotes: 1

Views: 88

Answers (3)

Zoleas
Zoleas

Reputation: 4879

I agree with the comment of Till. Do something like that, if self.enemies is your original mutable array

NSArray * enemiesToRemove = [[NSMutableArray alloc] init];
for (Enemy * enemy in self.enemies) {
    if ([enemy colidesWithBullet]) {
        [enemiesToRemove addObject:enemy];
    }
}
[self.enemies removeObjectsInArray:enemiesToRemove];
[enemiesToRemove release];

Upvotes: 3

madmik3
madmik3

Reputation: 6983

Removing items from an array that you are itterating over can be tricky. You can do something like Zoleas suggested or you can avoid enumerating the list and start at the last element and check backwards to the first element removing elements that need removed. This way you can ensure that you are never removing an element that will effect the index of later elements.

for(int i=[array count]-1; i >=0  :i--)
{
  bool needsRemoved = /* your code here */;
  if (needsRemoved)
  {
     [ary removeObjectAtIndex:i]
  }
}

Upvotes: 1

Daniel
Daniel

Reputation: 22405

Basically you cant remove or add from the array while its being enumerated, and since you seem to be iterating the array often then you will probably get this exception a lot, one choice is to lock your array while you iterate and while you remove using a @synchronized block on the array, this will guarantee that you wont be modifying the array while iterating...Down side to this approach is that you will have the iterations and add/remove operations waiting on each other...

 @synchronized(myArray)
{
    //iterate through myArray
}

@synchronized(myArray)
{
   //mutate the array
}

Upvotes: 1

Related Questions