iOS 關(guān)于數(shù)組刪除的時(shí)候使用enumerateObjectsUsingBlock刪除不全

背景:今天使用enumerateObjectsUsingBlock刪除數(shù)組里面的對(duì)象元素出現(xiàn)刪除不全的問(wèn)題。

[indexSceneList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"obj===>%@",obj);
        NSLog(@"idx===>%lu",(unsigned long)idx);

        SceneItem *customIndexSceneItem = obj;
        NSLog(@"customIndexSceneItem.uid=>%@",customIndexSceneItem.uid);
        for (SceneItem *item in defaultSceneList) {
            NSLog(@"item.uid==>%@==>%@",item.uid,customIndexSceneItem.uid);
            if ([item.uid isEqualToString:customIndexSceneItem.uid]) {
                [indexSceneList removeObject:customIndexSceneItem];
            }
        }
    }];

原因:當(dāng)發(fā)現(xiàn)符合刪除條件的時(shí)候?qū)⒃撛貜臄?shù)組里刪除,這是數(shù)組里的元素會(huì)向前移動(dòng),各個(gè)元素的下標(biāo)會(huì)-1,但是遍歷過(guò)程是按idx遞增的,所以下一個(gè)獲取的元素是跳過(guò)了一個(gè)下標(biāo)的元素,也就是刪除一個(gè)再遍歷獲取到的元素實(shí)際上是原始數(shù)組跳過(guò)一個(gè)下標(biāo)的元素。簡(jiǎn)而言之,就是刪除一個(gè)元素以后數(shù)組元素位置前移,但是我們遍歷的元素的索引又向后加,就剛好完美錯(cuò)過(guò)。
解決方案:倒敘刪除

for (NSInteger i = [indexSceneList count] - 1; i >= 0; i--) {
        SceneItem *customIndexSceneItem = [indexSceneList objectAtIndex:i];
        for (SceneItem *item in defaultSceneList) {
            NSLog(@"item.uid==>%@==>%@",item.uid,customIndexSceneItem.uid);
            if ([item.uid isEqualToString:customIndexSceneItem.uid]) {
                [indexSceneList removeObjectAtIndex:i];
            }
        }
    }
?著作權(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)容