解决bug*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.’

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.'

当程序出现这个提示的时候,是因为你一边遍历数组,又同时修改这个数组里面的内容,导致崩溃,

方法一:

网上的方法如下:这种方法就是在定义一个一模一样的数组,便利数组A然后操作数组B

    NSMutableArray * arrayTemp = xxx; 

    NSArray * array = [NSArray arrayWithArray: arrayTemp];  

    for (NSDictionary * dic in array) {        

        if (condition){            

            [arrayTemp removeObject:dic];

        }       

    }

方法二:

利用block来操作,根据查阅资料,发现block便利比for便利快20%左右,这个的原理是这样的:
找到符合的条件之后,暂停遍历,然后修改数组的内容

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

你可能感兴趣的:(解决bug*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.’)