Friday, May 31, 2013

NSArray objectsAtIndexes example in Objective C (iOS).

NSArray objectsAtIndexes

Returns an array containing the objects in the array at the indexes specified by a given index set.

- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes

Return Value
An array containing the objects in the array at the indexes specified by indexes.

Discussion of [NSArray objectsAtIndexes]
The returned objects are in the ascending order of their indexes in indexes, so that object in returned array with higher index in indexes will follow the object with smaller index in indexes.

Raises an NSRangeException if any location in indexes exceeds the bounds of the array, of if indexes is nil.

NSArray objectsAtIndexes example.
[yourArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(3, yourArray.count - 3)]];

Example of [NSArray objectsAtIndexes].
NSIndexSet *indexes = [activeItems indexesOfObjectsPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqualToString:@"1"];
Once you have the indexes, you can get the subset of the original array, containing just the objects you are interested in, using [NSArray objectsAtIndexes:] (reference):

NSArray *subset = [activeItems objectsAtIndexes:indexes];

NSArray objectsAtIndexes example.
One option would be to convert the array of indexes to an NSIndexSet and then use objectsAtIndexes:

NSArray *objects = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G"];
NSArray *indexArray = @[@(0), @(2), @(6)];

NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSNumber *number in indexArray) {
    [indexSet addIndex:[number unsignedIntegerValue]];
NSArray *filtered = [objects objectsAtIndexes:indexSet];

End of NSArray objectsAtIndexes example article.