Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use removeObject: during enumerateObjectsUsingBlock:? [duplicate]

This code runs without crashing and I don't see anything in the documentation, but is it really safe?

[mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // do some stuff to obj before removing it
    [mutableArray removeObject:obj];
}];
like image 385
lavoy Avatar asked Dec 20 '22 07:12

lavoy


2 Answers

I think this should not be done.

As in enumeration the object is treated as const.

I tried same code, I received following error:

Collection <__NSArrayM: 0x10053b8d0> was mutated while being enumerated.

The Code:

NSMutableArray *mutableArray=[NSMutableArray new];
[mutableArray addObject:@"A"];
[mutableArray addObject:@"Ab"];
[mutableArray addObject:@"Ac"];
[mutableArray addObject:@"Ad"];

[mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // do some stuff to obj before removing it
    [mutableArray removeObject:obj];
    NSLog(@"--->%@",mutableArray);
}];
like image 151
Anoop Vaidya Avatar answered May 10 '23 23:05

Anoop Vaidya


This is something you should never do. Instead, collect all the element indexes into an NSMutableIndexSet object and then later use the removeObjectsAtIndexes: to remove all of the objects at once.

like image 27
steve882 Avatar answered May 10 '23 23:05

steve882