Kristen Martinson
Kristen Martinson

Reputation: 1869

How to get indices of NSArray using something like indexOfObject?

I can use [NSArray indexOfObject: NSString] to get an index of my search for 1 item. But what can I use or do to get an array of returned indices from my search?

thanks

Upvotes: 2

Views: 2475

Answers (2)

outis
outis

Reputation: 77400

To get multiple indices, you can use indexesOfObjectsPassingTest::

// a single element to search for
id target;
// multiple elements to search for
NSArray *targets;
...
// every index of the repeating element 'target'
NSIndexSet *targetIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqual:target];
    }];

// every index of every element of 'targets'
NSIndexSet *targetsIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
        return [targets containsObject:obj];
    }];

Support for blocks were added in iOS 4. If you need to support earlier versions of iOS, indexesOfObjectsPassingTest: isn't an option. Instead, you can use indexOfObject:inRange: to roll your own method:

@interface NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target;
@end

@implementation NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target {
    NSRange range = NSMakeRange(0, [self count]);
    NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
    NSUInteger idx;
    while (range.length && NSNotFound != (idx = [self indexOfObject:target inRange:range])) {
        [indexes addIndex: idx];
        range.length -= idx + 1 - range.location;
        range.location = idx + 1;
    }
    return [indexes autorelease];
}
@end

Upvotes: 6

Chris Gregg
Chris Gregg

Reputation: 2382

If you don't have access to indexOfObjectsPassingTest, as @outis recommends, you could use indexOfObject:inRange: and loop over the results, updating the range to start after the last result finished, and updating the results into your own NSIndexSet, or NSMutableArray, etc.

Upvotes: 1

Related Questions