Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutation within fast enumeration?

Actually I receive a somehat strange exception: I iterate a MutableDictionary and want to aset a new value in it:

    selectionIndex = [NSMutableDictionary dictionaryWithDictionary:selection];
    NSString *whatever = @"999999";
    id keys;
    NSEnumerator *keyEnum = [selectionIndex keyEnumerator];

    while (keys = [keyEnum nextObject]) 
    {
        [selectionIndex setObject:whatever forKey:keys];
    }

Btw, selection, that is passed to this method is a MutableDictionary. If I run this code, I receive the following exception:

2011-12-05 15:28:05.993 lovelini[1333:207] * Terminating app due to uncaught exception 'NSGenericException', reason: '* Collection <__NSCFDictionary: 0x6a33ed0> was mutated while being enumerated.{type = mutable dict, count = 8, entries => 0 : {contents =

Ok, I know that I can't change NSDictionary, but as far as I see it, I don't! So why do I get this exception? Is this a restriction of Fast Enumeration??? As far as I know it is not possible to add or remove entries within Fast Enumeration, but I don't add or remove anything?!

like image 550
usermho Avatar asked Jan 28 '26 07:01

usermho


1 Answers

You cannot make any changes to a collection while enumerating it. You could instead enumerate the keys of the dictionary instead of the dictionary itself:

for (NSString *key in selectionIndex.allKeys) {
    [selectionIndex setObject:whatever forKey:key];
}
like image 142
omz Avatar answered Jan 30 '26 21:01

omz