5

Can I remove items that I am looping through in an Objective-C for loop without side effects?

For example, is this ok?

for (id item in items) {
   if ( [item customCheck] ) {
      [items removeObject:item];   // Is this ok here?
}

3 Answers 3

12

No, you'll get an error if you mutate the array while in a fast enumeration for loop. Make a copy of the array, iterate over it, and remove from your original.

NSArray *itemsCopy = [items copy];

for (id item in itemsCopy) {
   if ( [item customCheck] )
      [items removeObject:item];   // Is this ok here
}

[itemsCopy release];
2
  • Wouldn't this skip 1 element since each array element gets shifted by 1 when deletion happens. Feb 10, 2014 at 11:53
  • No, we're not removing the item from the display using an index with this example. NSMutableArray's removeObject: method looks through the array and removes the first reference to the object it finds. Internally the call uses indexOfObject: and removeObjectAtIndex: to do it. This could be a performance hit if you have a large enough array. You could optimize it a bit by tracking the index but then you would have to adjust it for deletions.
    – McCygnus
    Feb 10, 2014 at 19:30
3

Nope:

Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.

Options for changing an array that you want to enumerate through are given in Using Enumerators: either copy the array and enumerate through, or build up an index set that you use after the loop.

1
  • thanks - the suggestion from McCygnus seems to adhere to this so it looks ok
    – Greg
    Apr 28, 2011 at 23:49
0

you can remove like this:

    //Create array
    NSMutableArray* myArray = [[NSMutableArray alloc] init];

    //Add some elements
    for (int i = 0; i < 10; i++) {
        [myArray addObject:[NSString stringWithFormat:@"i = %i", i]];
    }

    //Remove some elements =}
    for (int i = (int)myArray.count - 1; i >= 0 ; i--) {
        if(YES){
            [myArray removeObjectAtIndex:i];
        }
    }
1
  • That i-- makes the diference. ;) May 15, 2015 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.