这段代码有什么问题?我得到了
Collection <NSCFArray: 0x101e1b6d0> was mutated while being enumerated
是NSMutableArray,而不是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];
答案 0 :(得分:6)
答案 1 :(得分:6)
在迭代它时,你不能改变(改变)一个集合,因为迭代器对象也需要改变。您应该将要删除的对象添加到数组中,然后将其删除。
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];