views:

3032

answers:

5

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?

+1  A: 

From The Objective-C 2.0 Programming Language, you cannot modify the collection being enumerated:

Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.

mouviciel
A: 

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

Squeegy
+5  A: 

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];
}
Andrew Grant
+4  A: 

The line

[aCollection addObject:bar]

is your problem. You cannot modify aCollection while enumerating it. The better approach would be to create a temporary NSMutableArray, add bar to that, then call [aCollection addObjectsFromArray:] with your temporary array.

For example:

NSMutableArray *foundObjects = [NSMutableArray array];
for (NSDictionary *aDictionary in aCollection) {
    if ([[bar objectForKey:@"id"] isEqual:[aDictionary objectForKey:@"id"]])
       break;

    [foundObjects addObject:bar];
}
[aCollection addObjectsFromArray:foundObjects];
Alex
A: 

If this is a multithreaded application you can employ the use of NSLock or some other locking mechanism.

http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/chapter_5_section_7.html

Evan