iOS之解決崩潰Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.


 

崩潰提示:Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <CALayerArray: 0x14df0bd0> was mutated while being enumerated.'

 

當程序出現這個提示的時候,是因為你一邊便利數組,又同時修改這個數組里面的內容,導致崩潰,網上的方法如下:

NSMutableArray * arrayTemp = xxx; 

    NSArray * array = [NSArray arrayWithArray: arrayTemp];  

    for (NSDictionary * dic in array) {        

        if (condition){            

            [arrayTemp removeObject:dic];

        }       

    }

這種方法就是在定義一個一模一樣的數組,便利數組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%左右,這個的原理是這樣的:

找到符合的條件之后,暫停遍歷,然后修改數組的內容

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM