< Back to Demonfall, Game Dev

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

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 *