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.'數組

 

當程序出現這個提示的時候,是由於你一邊便利數組,又同時修改這個數組裏面的內容,致使崩潰,網上的方法以下:app

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而後操做數組Bexception

今天終於找到了一個更快接的刪除數組裏面的內容以及修改數組裏面的內容的方法:

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%左右,這個的原理是這樣的:

找到符合的條件以後,暫停遍歷,而後修改數組的內容

相關文章
相關標籤/搜索