An earlier problem was discovered while updating the old project with new requirements. Deleting an object specified in the array caused a crash during array traversal.

The reason is that in the case of array traversal, the index of the object is not updated. In this case, the index error of the next loop after deleting an object causes the array out of bounds problem and causes the crash.

Solution Use reverse order for loop to delete

for (NSInteger i=self.viewModel.shopGoods.count-1; i> =0; --i) {
    WGShopCarModel *shopModel=[self.viewModel.shopGoods objectAtIndex:i];
    if (shopModel.goodsList.count= =0) {[self.viewModel.shopGoods removeObject:shopModel]; }}Copy the code

This is correct but awkward, so enumerate is recommended

[self.viewModel.shopGoods enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
    WGShopCarModel *shopModel=[self.viewModel.shopGoods objectAtIndex:idx];
    if (shopModel.goodsList.count= =0) {[self.viewModel.shopGoods removeObject:shopModel]; }}];Copy the code

NSEnumerationReverse Indicates the reverse sequence. NSEnumerationConcurrent Indicates the positive sequence