I have an array and as I iterate through the array I wanted to replace the item as well. Is this not possible and will cause crahes if I do so? Here’s the code:
for (int i = 0; i < [highlightItemsArray count]; i++){
//replace the from array with the new one
NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionaryWithDictionary:highlightItem];
[tempDictionary setObject:[newHighlightItem objectForKey:@"from"] forKey:@"from"];
[highlightItemsArray replaceObjectAtIndex:i withObject:tempDictionary];
[indexes addIndex:i];
}
just wanted to know if this is legit in objective-C? if not then what is the alternative of doing so?
You above code look good.
If it crashes it is not due to altering of your array.
However in old style loops ( while, for(;;), dowhile ) you can change any of these
1. initialiser (but this is executed just once)
2. counter
3. condition.
But in case of fast enumeration you can not do all these.
Therefore if you incorporate your above code with for(… in …) it will throw an error, saying trying to mutate an immutable object. Even though you define your counter and/or array immutable fast enumeration treats them as immutable.