Search code examples
ios4iphone-sdk-3.0enumeration

replacing objects in array while enumerating?


I am sending an update for my app that will require that the users databases be updated. I am storing data in a property list. Basically a every point in the array are NSMutableDictionaries and I need to add keys, replace keys etc.

I attempted the following, however it generates an NSException,

for (NSMutableDictionary *dict in myArray) {

    if ([dict objectForKey:@"someKey"] == nil) {

        //Extract the value of the old key and remove the old key
        int oldValue = [[dict objectForKey:@"key1"] intValue];
        [dict removeObjectForKey:@"key1"];

        [dict setValue:[NSString stringWithFormat:@"%d pts", oldValue] forKey:@"newKey"];

        //Add new keys to dictionnary
        [dict setValue:@"some value" forKey:@"key2"];
        [dict setValue:@"some value" forKey:@"key3"];
        [dict setValue:@"some value" forKey:@"key4"];

        [self.myArray replaceObjectAtIndex:index withObject:dict];

    }

What should I do to update my data in the above manner?


Solution

  • The problem is that you cannot modify the array you are iterating over with fast enumeration.

    The code snippet has no need for that replaceObjectAtIndex:withObject: call at all, as you replace the object with the very same object! So if you remove that line everything should work.

    Generally, you can avoid similar problems if you use the plain old for loop with indexing, i.e.

    for (int i = 0; i < [array count]; i++) {
        id obj = [array objectAtIndex:i];
        // ...
    }
    

    as this will not mess up with fast enumeration.