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

人盡茶涼 提交于 2019-11-30 07:27:52
dasblinkenlight

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

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;
Pawan Ahire

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;

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't modify the array while looping through it with the for...in... control statement.

Try:

    NSArray *compareArray = [updatedLocalityArray copy];
    for (NSString *test in compareArray)
    // ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!