objective-cfor-loopnsmutablearraynsarrayfast-enumeration

Remove items in a for loop without side effects?


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?
}

Solution

  • 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];