解决Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.-

当程序出现这个提示的时候,是因为你一边便利数组,又同时修改这个数组里面的内容,导致崩溃,错误的方法如下:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddSelectFuwushiCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
     ResponseFuwushiListModel *model =_dataList[indexPath.row];
       if (cell.selectBtn.selected) {
       cell.selectBtn.selected = NO;
//           NSMutableArray *tempArray = [[NSMutableArray alloc]initWithArray:_selectedArr];
           for (ResponseFuwushiListModel *item in _selectedArr) {
               if ([item.userId isEqualToString:model.userId]) {
                   [_selectedArr removeObject:item];
               }
           }
           
           
    }else{
         cell.selectBtn.selected = YES;
        [_selectedArr addObject:model];
    }
    
}

这种方法就是对数组_selectedArr 遍历然后操作

今天终于找到了一个更快捷的删除数组里面的内容以及修改数组里面的内容的方法:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddSelectFuwushiCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    ResponseFuwushiListModel *model =_dataList[indexPath.row];
    if (cell.selectBtn.selected) {
        cell.selectBtn.selected = NO;
        [_selectedArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ResponseFuwushiListModel *model1 = (ResponseFuwushiListModel*)obj;
            if ([model1.userId isEqualToString:model.userId]) {
                *stop = YES;
                if (*stop == YES) {
                    [_selectedArr removeObject:model1];
                }
            }
            if (*stop) {
                NSLog(@"array is %@",_selectedArr);
            }
        }];
    }else{
        cell.selectBtn.selected = YES;
        [_selectedArr addObject:model];
    }
    
}

利用block来操作,发现block遍历比for遍历快20%左右,这个的原理是这样的:
找到符合的条件之后,暂停遍历,然后修改数组的内容
这种方法非常简单有效

你可能感兴趣的:(解决Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.-)