Sometimes we may face a situation when we need to remove objects from an array while iterating through the same array. We cannot remove elements from the same array on which we are fast enumerating (for in loop). And if we use the traditional "for loop" then the indexes and count of the array change which becomes tricky to handle. So in such condition we can use one of 3 solutions :
- Copy objects to another temp array, iterate on temp array and remove elements from main array.
- Iterate in reverse order from last to first index.
- Use NSIndexSet to remove multiple objects in one go.
Following example methods show how to remove even numbers from an array :
// using reverse loop
-(void)removeElementsFromArrayUsingReverseLoop {
NSMutableArray *arr = [@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8"] mutableCopy];
NSLog(@"original array %@",arr);
for (int i = arr.count-1; i>=0; i--) {
int element = [arr[i] intValue];
if (element%2==0) {
[arr removeObjectAtIndex:i];
}
}
NSLog(@"array after removing %@",arr);
}
// using NSIndexSet
-(void)removeMultipleElementsFromArray {
NSMutableArray *arr = [@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8"] mutableCopy];
NSLog(@"original array %@",arr);
NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
for (NSString *str in arr) {
if ([str intValue]%2 == 0) {
[indexset addIndex:[arr indexOfObject:str]];
}
}
[arr removeObjectsAtIndexes:indexset];
NSLog(@"array after removing %@",arr);
}
0 Comment(s)