用for循环遍历了可变对象,同时对可变对象进行增加、删除操作会报此错误:
- reason: Collection <__NSArrayM: 0x60800005bd50> was mutated while being enumerated
解决办法:
① 操作完成立刻跳出循环
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5" , nil];
for (NSString *str in array) {
if ([str isEqualToString:@"2"]) {
[array removeObject:@"0"];
break;
}
}
注意:用 continue 跳出还是会报错,必须结束循环
② 遍历copy后的对象
for (NSString *str in [array copy]) {
if ([str isEqualToString:@"2"]) {
[array addObject:@"0"];
}
}
③ 开线程去执行操作
for (NSString *str in array) {
if ([str isEqualToString:@"2"]) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[array addObject:@"0"];
});
}
}
④ 更换遍历方式
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isEqualToString:@"2"]) {
[array removeObject:obj];
// *stop = true;
}
}];
话题延伸:
@property (atomic, strong)NSMutableArray *array;
原子属性修饰的对象是安全的,那么以上属性是安全的吗?
面试中可能会遇到这样的问题,atomic修饰只是说此对象setter & getter 方法是安全的,对象本身并不是安全的;
@property (nonatomic, copy)NSMutableArray *array;
对这个数组进行增加、删除操作会报错吗?
会, 打印对象的类型就看到了:
@property (nonatomic, copy)NSMutableArray *array1;
@property (nonatomic, strong)NSMutableArray *array2;
NSLog(@"%@, ", [self.array1 class]);
NSLog(@"%@, ", [self.array2 class]);
2016-11-14 17:55:15.053 TestArray[26252:1532398] __NSArrayI,
2016-11-14 17:55:15.055 TestArray[26252:1532398] __NSArrayM,
没有经过copy修饰的是Mutable类型,经过copy修饰的是Immutable类型
以上代码均经过测试,如有不妥的地方希望指正!