How to edit an array as you’re looping through it

Posted on

in

,

I was getting random crashes and I wasn’t sure why. Then I found out changing an array inside a loop that was going through each of the array’s items causes this (makes sense when you think about it) What you should do is inside the loop, collect up all the items to be removed inside the loop into an temporary array, then only after the loop has finished remove any items in the array that’s stored in the temporary array.

NSMutableArray *discardedItems = [NSMutableArray array]; //temp array
SomeObjectClass *item;
for (item in originalArrayOfItems) { // the loop
if ([item shouldBeDiscarded])
[discardedItems addObject:item]; //add items into temp array
}
//end loop
[originalArrayOfItems removeObjectsInArray:discardedItems]; //remove items
that match the ones in the temp array from original array after the loop

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031