Question

Here is a snippet of code that enumerates through NSMutableArray *myArray and modifies each NSMutableDictionary within it. The problem I see with this code is that it's modifying while enumerating.

Code:

for (NSMutableDictionary *aDict in myArray)
{
   theDate = [self convertTheDate:[aDict valueForKey:@"date"]];

   [aDict setValue:theDate forKey:@"date"];
}

[self passUpdatedDates:myArray];

How should I modify this to be safe code?

Was it helpful?

Solution

Your code should be fine (with the change to setObject:forKey: as Maddy described in his comment), as long as your array myArray really is an array of mutable dictionaries. If any of the dictionaries in the array are not mutable then this code will crash when you try to change the dictionary.

If that's the case then you will need to create a mutable copy of each dictionary, change the key in question, and then save the modified dictionary to the correct index in the array. To do THAT, you now have to deal with modifying an array as you are enumerating it.

The simple way to do this is to change from fast enumeration (for... in) to a for loop that counts through all the indexes and uses objectAtIndex to fetch each object, change it, and save it back to the array.

To continue to use fast enumeration, you can create a new mutable array that is the same size as myArray, loop through myArray with for... insyntax, and simply add each modified dictionary to the new mutable array. Then you are enumerating the source array with fast enumeration and creating a duplicate object in a separate array. This doubles your memory footprint but gives you the performance benefit of fast enumeration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top