Collection <__NSArrayM: 0x7fa1f2711910> was mutated while being enumerated

后端 未结 5 1284
轮回少年
轮回少年 2020-12-30 14:05

There are number of questions with similar title but none them of helped me.

but i can relate solution of this 'NSGenericException', reason: Collection <

相关标签:
5条回答
  • 2020-12-30 14:13

    if your current array is A,you can copy another same array called B,then you can enumerate B and operate A,then it will not crash.

    0 讨论(0)
  • 2020-12-30 14:16

    If your current array is A, you can copy another same array called B, then you can enumerate B and operate A,then it will not crash.

    You can not modify containers while enumerating them.

    NSMutableArray *tempArray = someArray.mutableCopy;
    
    0 讨论(0)
  • 2020-12-30 14:20

    You cannot delete items from a NSMutableArray while iterating it.

    There are several solutions to this:

    • Iterate a copy of the array

    or

    • Use an index-based for loop instead of the for each syntax.

    Not copying the array saves you an allocation and a few CPU cycles:

    for (int i = updatedLocalityArray.count-1 ; i >= 0 ; i--)
    {
        NSString *test = updatedLocalityArray[i];
        if ([test isEqualToString:tableViewCell.textLabel.text])
        {
            [updatedLocalityArray removeObjectAtIndex:i];
            NSLog(@"%@ *****", updatedLocalityArray);
        }
    }
    
    0 讨论(0)
  • 2020-12-30 14:27

    You can't modify the array while looping through it with the for...in... control statement.

    Try:

        NSArray *compareArray = [updatedLocalityArray copy];
        for (NSString *test in compareArray)
        // ...
    
    0 讨论(0)
  • 2020-12-30 14:31

    In you tableview deselect method, you wrote:

    for (NSString *test in updatedLocalityArray)
    {
        if ([test isEqualToString:tableViewCell.textLabel.text])
        {
            [updatedLocalityArray removeObject:test];
            NSLog(@"%@ *****", updatedLocalityArray);
        }
    }
    

    In that code you are enumerating through updatedLocalityArray and if you find a match you are removing that object from same array, this logic is causing the issue here. For fixing that you need to create local copy and do the changes in it and assign it back to the original array after the enumeration.

    NSMutableArray *tempArray = [updatedLocalityArray mutableCopy];
    for (NSString *test in updatedLocalityArray)
    {
        if ([test isEqualToString:tableViewCell.textLabel.text])
        {
            [tempArray removeObject:test];
            NSLog(@"%@ *****", tempArray);
        }
    }
    updatedLocalityArray = tempArray;
    
    0 讨论(0)
提交回复
热议问题