Friday, May 31, 2013

NSArray indexesOfObjectsPassingTest example in Objective C (iOS).

NSArray indexesOfObjectsPassingTest

Returns the indexes of objects in the array that pass a test in a given Block.

- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

The block to apply to elements in the array.
The block takes three arguments:
The element in the array.
The index of the element in the array.
A reference to a Boolean value. The block can set the value to YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.
The Block returns a Boolean value that indicates whether obj passed the test.

Return Value of [NSArray indexesOfObjectsPassingTest]
The indexes whose corresponding values in the array pass the test specified by predicate. If no objects in the array pass the test, returns an empty index set.

NSArray indexesOfObjectsPassingTest example.
NSIndexSet *indexes = [recipeArray indexesOfObjectsPassingTest:
        ^BOOL (id el, NSUInteger i, BOOL *stop) {
            NSString *recipeID = [(Recipe *)el recipe_id];
            return [keyArray containsObject:recipeID];
NSArray *results = [recipeArray objectsAtIndexes:indexes];

Example of [NSArray 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];

NSArray indexesOfObjectsPassingTest example.
- (NSIndexSet *)indexesMatchingObject:(id)anObject inArray:(NSArray *)anArray
    NSIndexSet *indexSet = [anArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqual:anObject];

    return indexSet;

End of NSArray indexesOfObjectsPassingTest example article.