Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C 2.0 and Fast Enumeration throwing exceptions

I have a block of code which is similar to the following:

for (NSDictionary *tmp in aCollection) {
   if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]])
   {
      break;
   }
   else
   {
      [aCollection addObject:bar];
       }
 }

Is this technically an exception in Objective-C 2.0? It appears you cannot mutate a collection with fast enumeration. This is the result of an error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <NSCFArray: 0x396000> was mutated while being enumerated.'

What's the best way to solve this?

like image 726
Coocoo4Cocoa Avatar asked Feb 16 '09 20:02

Coocoo4Cocoa


2 Answers

Well the way to solve it is not to mutate the array (e.g. add an object) while enumerating it :)

The problem here is that modifying the array by adding/removing elements could cause the enumeration values to become invalid, hence why it's a problem.

In your case The easiest way to solve this is fixing the bug in your code. Your code is doing the "else add" clause for every item in the array and I'm quite sure that's not what you want.

Try this;

bool found = false;
for (NSDictionary *tmp in aCollection)
{
   if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]])
   {
      found = true;
      break;
   }
}

if (!found)
{
 [aCollection addObject:bar];
}
like image 65
Andrew Grant Avatar answered Nov 18 '22 21:11

Andrew Grant


Make a copy of the collection and iterate through that. Then you can swap out or add to your original collection without issues.

like image 33
Alex Wayne Avatar answered Nov 18 '22 20:11

Alex Wayne