Changing a collection you are iterating is sometimes difficult to understand. There are good reasons to avoid it, even in your case there is a simple solution. (But these solutions break very fast, when you remove other elements of the array.)
There are some generic solutions:
A. Iterate over a copy
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];
NSArray *iterationArray = [array copy];
[iterationArray enumerateObjectsWithOptions: NSEnumerationReverse usingBlock:
^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isEqualToString:@"A"]) {
[array removeObject:obj];
} else if ([obj isEqualToString:@"B"]) {
[array removeObject:obj];
}
}];
B. Store objects to remove
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];
NSMutableArray *itemsToRemove = [NSMutableArray new];
[array enumerateObjectsWithOptions: NSEnumerationReverse usingBlock:
^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isEqualToString:@"A"]) {
[itemsToRemove addObject:obj];
} else if ([obj isEqualToString:@"B"]) {
[itemsToRemove addObject:obj];
}
}];
[array remveObjects:itemsToRemove];
All these ways to do it including your way may cause unexpected results, because -removeObject: removes all occurrences of the object in the array itself, what means the removal of all objects that are equal to the arg, including objects that are not identical.
C. Remove objects with that indexes
If you are iterating using an index – or can easily build an index – it is more efficient to store the indices and then remove with this one. This gives you the opportunity to differ between equal and identical objects. In your case
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];
NSMutableIndexSet *itemsToRemove = [NSMutableIndexSet new];
__block NSUInteger index=0;
[array enumerateObjectsWithOptions: NSEnumerationReverse usingBlock:
^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
{
if ([obj isEqualToString:@"A"])
{
[itemsToRemove addIndex:index];
} else if ([obj isEqualToString:@"B"]) {
[itemsToRemove addIndex:index];
}
index++;
}];
[array removeObjectsAtIndexes:itemsToRemove];
NSLog(@"%@", array);