Delete items in a for loop without side effects?

Is it possible to remove elements that I scroll in an Objective-C loop forwithout side effects?

For example, is this normal?

for (id item in items) {
   if ( [item customCheck] ) {
      [items removeObject:item];   // Is this ok here?
}
+5
source share
3 answers

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

NSArray *itemsCopy = [items copy];

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

[itemsCopy release];
+12
source

No:

Enumeration is "safe" - the enumerator is protected against mutations, so if you try to change the collection during the enumeration, an exception is thrown.

, , : , , , .

+3

you can delete 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];
        }
    }
0
source

All Articles