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?
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];
}
Make a copy of the collection and iterate through that. Then you can swap out or add to your original collection without issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With