Saturday, June 1, 2013

NSMutableArray removeObjectsAtIndexes example in Objective C (iOS).


NSMutableArray removeObjectsAtIndexes

Removes the objects at the specified indexes from the array.

- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes

Parameters
indexes
The indexes of the objects to remove from the array. The locations specified by indexes must lie within the bounds of the array.

Discussion of [NSMutableArray removeObjectsAtIndexes]
This method is similar to removeObjectAtIndex:, but allows you to efficiently remove multiple objects with a single operation. indexes specifies the locations of objects to be removed given the state of the array when the method is invoked, as illustrated in the following example.
NSMutableArray removeObjectsAtIndexes example.
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"a", @"two", @"b", @"three", @"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(@"array: %@", array);

// Output: array: (one, two, three, four)

Example of [NSMutableArray removeObjectsAtIndexes].
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
SomeObjectClass *item;
NSUInteger index = 0;

for (item in originalArrayOfItems) {
    if ([item shouldBeDiscarded])
        [discardedItems addIndex:index];
    index++;
}

[originalArrayOfItems removeObjectsAtIndexes:discardedItems];

NSMutableArray removeObjectsAtIndexes example.
NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:
    ^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [self shouldRemove:obj];
}];
[someList removeObjectsAtIndexes:indexesToBeRemoved];

End of NSMutableArray removeObjectsAtIndexes example article.