问题
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];
回答1:
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.
回答2:
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];
来源:https://stackoverflow.com/questions/9465709/app-crash-during-array-enumerating