0

What is wrong with this code ? I get

 Collection <NSCFArray: 0x101e1b6d0> was mutated while being enumerated

It is NSMutableArray, not NSArray

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

    [set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if([obj isEqualToString:@"third"])
         {
             [set removeObjectAtIndex:idx];
         }
     }];

    [pool drain];
foho
  • 779
  • 9
  • 20

2 Answers2

6

The problem is you're changing the array during enumeration. This is no-go.

Please read selected answer at

Best way to remove from NSMutableArray while iterating?

All you need is there.

Community
  • 1
  • 1
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
6

You can't mutate (change) a collection while you are iterating it because the iterator object would need to change too. You should add the objects you want to remove to an array and remove them afterwards.

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

NSMutableArray *arrayOfObjectsToRemove = [[NSMutableArray alloc] init];
[set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
 {
     if([obj isEqualToString:@"third"])
     {
         [arrayOfObjectsToRemove addObject:obj];
     }
 }];

[set removeObjectsInArray:arrayOfObjectsToRemove];

[pool drain];
James Webster
  • 31,873
  • 11
  • 70
  • 114