*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.'
當程序出現這個提示的時候,是因為你一邊遍歷數組,又同時修改這個數組里面的內容,導致崩潰,
方法一:
網上的方法如下:這種方法就是在定義一個一模一樣的數組,便利數組A然后操作數組B
NSMutableArray * arrayTemp = xxx;
NSArray * array = [NSArray arrayWithArray: arrayTemp];
for (NSDictionary * dic in array) {
if (condition){
[arrayTemp removeObject:dic];
}
}
方法二:
利用block來操作,根據查閱資料,發現block便利比for便利快20%左右,這個的原理是這樣的:
找到符合的條件之后,暫停遍歷,然后修改數組的內容
NSMutableArray *tempArray = [[NSMutableArray alloc]initWithObjects:@"12",@"23",@"34",@"45",@"56", nil];
[tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:@"34"]) {
*stop = YES;
if (*stop == YES) {
[tempArray replaceObjectAtIndex:idx withObject:@"3333333"];
}
}
if (*stop) {
NSLog(@"array is %@",tempArray);
}
}];