I would like to loop through my collection using a for-in loop, but read it's unsafe to modify the content of my data structure (which would be either a dictionary or an array) within such loop. Is that correct? Could it have any side effects? Should I use a for loop with index instead? Thank you.
-
1Check this out for detailed answers http://stackoverflow.com/questions/111866/best-way-to-remove-from-nsmutablearray-while-iterating – msk Aug 03 '12 at 18:21
2 Answers
As long as you don't add or delete objects, you are OK. That is, if an object in the collection is a mutable object, and you change something about that, its fine. Its only when you go deleting, adding or replacing objects to the collection that you get into trouble.

- 40,852
- 12
- 92
- 138
-
Insightful. That is just what I need to know, and to do. Thank you! – ratsimihah Aug 03 '12 at 18:03
-
I would also suggest learning and using the "enumerate....WithBlock" methods for the various collections. They generate much less code and are faster than the older for(id foo in abc) approach. Apple really stresses this point at the WWDCs I've been to. They seem foreign at first but you quickly learn to love them. Also you can modify the first block parameter (normally id obj) to say "NSDictionary *dict" to avoid having to cast in block. – David H Aug 03 '12 at 18:09
-
I see. I'm not very familiar with blocks yet, and a bit short on time, so I'll add that to my optimization to-do list. Thanks for the suggestion. – ratsimihah Aug 03 '12 at 18:12
The simple answer is, yes, in theory it can have side effects. It depends on what you're doing in the loop. Without more information, I'd say to sit down with a pencil and paper and make a reasoned, mathematical argument (induction optional but recommended) to show that this process will never gunk up your data.
If you're modifying the contents of your array (if it's a pixel array, changing colors, for example), you're likely to not run into too much trouble if you plan your code well. If you're adding, deleting, or moving elements, proceed with caution.

- 401
- 3
- 11
-
Thank you. Glad to see your answer is in agreement with the previous one. – ratsimihah Aug 03 '12 at 18:05