首页 > 代码库 > Bug-iOS: Collection <__NSArrayM: 0x> was mutated while being enumerated.
Bug-iOS: Collection <__NSArrayM: 0x> was mutated while being enumerated.
//init a NSArray NSMutableArray *arr2 = [NSMutableArray array]; for (int i=0; i<10; ++i) { NSMutableDictionary *d = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d", i], @"a", nil]; [arr2 addObject:d]; } //Wrong for (NSMutableDictionary *s in arr2) { if ([s[@"a"] isEqualToString:@"3"]) { [arr2 removeObject:s]; //while here is safe for s[@"a"] = @"eeee"; } } //Safe 1. [arr2 enumerateObjectsUsingBlock:^(NSMutableDictionary *obj, NSUInteger idx, BOOL *stop) { if ([obj[@"a"] isEqualToString:@"3"]) { *stop = YES; [arr2 removeObject:obj]; // or obj[@"a"] = @"4ewewewe"; } }]; //Safe 2. NSArray *tmp = [NSArray arrayWithArray:arr2]; for (NSMutableDictionary *s in tmp) { if ([s[@"a"] isEqualToString:@"3"]) { s[@"a"] = @"eeee"; [arr2 removeObject:s]; } }
PS: 搜一句补充的话
//forin 循环中的便利内容不能被改变, 是因为如果改变其便利的内容会少一个, 而系统是不会允许这个发生的所以就会crash...但是当改变最后一个的内容时, 就不会crash, 是因为此时遍历已经结束, 结束之后对内容做修改是允许的 。
Bug-iOS: Collection <__NSArrayM: 0x> was mutated while being enumerated.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。