控制臺的Log:Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0x2811ebed0> was mutated while being enumerated.’
一、原因:
1、某個數(shù)組在遍歷的時候,同時又在修改數(shù)組中的內(nèi)容,才導(dǎo)致的崩潰。
2、for in 方法的原理是根據(jù) enumerator對象內(nèi)部的計數(shù)器,調(diào)用nextObject方法來實現(xiàn)返回下一個數(shù)組元素的,知道元素全部返回就會返回nil,這就代表著整個enumerator對象就遍歷完成了。需要注意的是以這種原理來遍歷enumrator對象的話, 無論對這個對象做什么操作, 對象的計數(shù)器都不會被重置!
二、解決方案:
方案一:新創(chuàng)建一個臨時的數(shù)組,將原始數(shù)組的數(shù)據(jù)拷貝到新的臨時數(shù)組;代碼如下:
NSMutableArray *dataArray = xxx;
NSArray *tmpArr = [NSArray arrayWithArray: dataArray];
for (NSDictionary *dic in tmpArr) {
if (condition){
[dataArray removeObject:dic];
}
}
方案二:使用帶有block的數(shù)組NSArray/NSMutableArray的系統(tǒng)API,找到符合條件的時候,暫停遍歷,對數(shù)組的內(nèi)容進(jìn)行修改。代碼如下:
NSMutableArray *dataArray = xxx;
dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (condition) {
*stop = YES;
if (*stop == YES) {
[dataArray replaceObjectAtIndex:idx withObject:@"ooo"];
}
}
}
參考的文章:
http://www.itdecent.cn/p/1a3065a07cbc
http://www.itdecent.cn/p/c2678ff90e46