Get NSIndexSet from NSArray

cocoafan picture cocoafan · May 25, 2009 · Viewed 12.3k times · Source

NSArray has useful methods to find objects for specified indexes

// To find objects by indexes
- (id)objectAtIndex:(NSUInteger)index
- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes

// To find index by object
- (NSUInteger)indexOfObject:(id)anObject

However, I want to get NSIndexSet (multiple indexes) for given objects. Something like:

- (NSIndexSet *)indexesOfObjects:(NSArray *)objects

This method does not exist for NSArray. Am I missing something? Does someone know another standard method? Otherwise I have to write this as a category method.

Answer

Oliver Schönherr picture Oliver Schönherr · Feb 6, 2013

Newer NSArray versions (OSX 10.6 and iOS 4) provides the indexesOfObjectsPassingTest: method.

NSIndexSet *indexesOfObjects = [[array1 indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [array2 containsObject:obj];
}];