iOS for in 快速遍历的时候 找到满足条件的元素删除 会导致Carsh

for in 遍历 崩溃:

            for (CataloguizeModel * sortModel in self.gameListArray) {
                    if (sortModel.is_last_play_blind == 1) {
                    CataloguizeModel *newModel = [[CataloguizeModel alloc] init];
                    newModel = sortModel;
                    [self.gameListArray removeObject:sortModel];
                    [self.gameListArray insertObject:newModel atIndex:0];
                  }
            }

崩溃原因:

        <_NSArrayM : >was mutated while being enumerated

解决方法:

 [self.gameListArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CataloguizeModel * sortModel = [[CataloguizeModel alloc] init];
                sortModel = obj;
                if (sortModel.is_last_play_blind == 1) {
                    *stop = YES;
                    if (*stop == YES) {
                        [self.gameListArray removeObject:obj];
                        [self.gameListArray insertObject:sortModel atIndex:0];
                    }
              }
    }];

原因分析:
可能是数组越界,因为for in 快速遍历 array.count 不会改变。当我们正序快速遍历时,如果删除了一个,那么没有遍历到的元素位置都会往前移动一位,这样系统就无法确定接下来遍历是从删除位置开始呢,还是从删除位置下一位开始呢?这样就造成程序crash了。比如数组有5个元素,删除了一个。正常情况下,array.count == 4 ,但是for in 快速遍历的结果是 array.count == 5 ,所以导致数据越界。造成Crash。

网上找到其它的解决办法:
1:使用for循环遍历。因为i < array.count,这个判断条件中,当数组元素个数变化时,array.count也在变,就不会出现数组越界的情况
2.逆序遍历 。因为逆序遍历时,遇到匹配的元素删除后,位置改变的是遍历过得元素,而没有遍历到的元素位置却没有改变,所以遍历能够正常进行

你可能感兴趣的:(iOS for in 快速遍历的时候 找到满足条件的元素删除 会导致Carsh)