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

 

bug:

今天作项目的时候遇到了这样一个崩溃信息:数组

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

 

2017-06-22 16:45:42.229 ViewTest[2638:c07] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.'app

当程序出现这个提示的时候,是由于你一边便利数组,又同时修改这个数组里面的内容,致使崩溃,网上的方法以下:post

 

 NSMutableArray * arrayTemp = xxx; spa

    NSArray * array = [NSArray arrayWithArray: arrayTemp];  rem

    for (NSDictionary * dic in array) {        it

        if (condition){            io

            [arrayTemp removeObject:dic];table

        }       class

    }原理

 

这种方法就是在定义一个如出一辙的数组,便利数组A而后操做数组B

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

 

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

        }

    }];


利用block来操做,根据查阅资料,发现block便利比for便利快20%左右,

这个的原理是这样的:

找到符合的条件以后,暂停遍历,而后修改数组的内容

这种方法很是简单哟

相关文章
相关标签/搜索