问题描述:当我们需要通过遍历数组过滤的时候,一般会考虑以下写法,这种写法 会引起crash
*** Collection <__NSArrayM: 0x7fddedfca720> was mutated while being enumerated.
1 NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithObjects:@"1",@"1",@"2",@"1",@"1",@"1",@"1",@"1",@"1",@"1", nil]; 2 3 for (NSString *numStr in mutableArray) { 4 5 if ([numStr isEqualToString:@"2"]) { 6 7 [mutableArray removeObject:numStr]; 8 9 } 10 11 }
问题解决:可以使用 方法
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
来避免这个crash
[mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj isEqualToString:@"2"]) { [mutableArray removeObject:obj]; } }];
还可以拷贝一份数组来操作如:
1 NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithObjects:@"1",@"1",@"2",@"1",@"1",@"1",@"1",@"1",@"1",@"1", nil]; 2 NSArray *array = [NSArray arrayWithArray:mutableArray]; 3 for (NSString *numStr in array) { 4 if ([numStr isEqualToString:@"2"]) { 5 [mutableArray removeObject:mutableArray]; 6 } 7 }