*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.'
當(dāng)程序出現(xiàn)這個(gè)提示的時(shí)候,是因?yàn)槟阋贿叡闅v數(shù)組,又同時(shí)修改這個(gè)數(shù)組里面的內(nèi)容试和,導(dǎo)致崩潰,
方法一:
網(wǎng)上的方法如下:這種方法就是在定義一個(gè)一模一樣的數(shù)組蜓堕,便利數(shù)組A然后操作數(shù)組B
NSMutableArray * arrayTemp = xxx;
NSArray * array = [NSArray arrayWithArray: arrayTemp];
for (NSDictionary * dic in array) {
if (condition){
[arrayTemp removeObject:dic];
}
}
方法二:
利用block來操作妹萨,根據(jù)查閱資料孵睬,發(fā)現(xiàn)block便利比for便利快20%左右,這個(gè)的原理是這樣的:
找到符合的條件之后牌芋,暫停遍歷蚓炬,然后修改數(shù)組的內(nèi)容
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);
}
}];