App crash during array enumerating

柔情痞子 提交于 2019-12-12 03:19:30

问题


What is wrong with this code ? I get

 Collection <NSCFArray: 0x101e1b6d0> was mutated while being enumerated

It is NSMutableArray, not NSArray

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

    [set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if([obj isEqualToString:@"third"])
         {
             [set removeObjectAtIndex:idx];
         }
     }];

    [pool drain];

回答1:


The problem is you're changing the array during enumeration. This is no-go.

Please read selected answer at

Best way to remove from NSMutableArray while iterating?

All you need is there.




回答2:


You can't mutate (change) a collection while you are iterating it because the iterator object would need to change too. You should add the objects you want to remove to an array and remove them afterwards.

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

NSMutableArray *arrayOfObjectsToRemove = [[NSMutableArray alloc] init];
[set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
 {
     if([obj isEqualToString:@"third"])
     {
         [arrayOfObjectsToRemove addObject:obj];
     }
 }];

[set removeObjectsInArray:arrayOfObjectsToRemove];

[pool drain];


来源:https://stackoverflow.com/questions/9465709/app-crash-during-array-enumerating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!