was mutated while being enumerated.錯(cuò)誤解決方法

需求是遍歷一個(gè)存 model 的數(shù)組 如果 id相同就刪除
我寫的是

for (UserModel*model in self.userArray) {
        if (model.uId == deleteId) {
           [self.userArray removeObject:model];
        }
    }

然后崩潰了。。。原因是Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.’在枚舉的時(shí)候發(fā)生了變化

然后在網(wǎng)上查到 是因?yàn)樾薷牧吮闅v對(duì)象 所以導(dǎo)致崩潰
然后我就想到辦法

BOOL isContain = NO;
    for (UserModel *model in self.userArray) {
        if (model.uId == deleteId) {
            isContain = YES;
        }
    }
    if (isContain) {
        [self.userArray removeObject:model];
    }

然后在網(wǎng)上找到其他辦法

一、

定義一個(gè)臨時(shí)數(shù)組 = self.userArray
然后遍歷臨時(shí)數(shù)組,但是操作self.userArray;

二、

利用block

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);
 
}
 
}];

此方法的好處是 這個(gè)便利方法 比for 遍歷更快, 因?yàn)榇朔椒ㄕ业椒系臈l件后就會(huì)停止遍歷 然后修改數(shù)組。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容