Friday, May 31, 2013

NSArray indexOfObjectPassingTest example in Objective C (iOS).

NSArray indexOfObjectPassingTest

Returns the index of the first object in the array that passes a test in a given Block.

- (NSUInteger)indexOfObjectPassingTest:(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. Returning YES will stop further processing of the array.

Return Value of [NSArray indexOfObjectPassingTest]
The lowest index whose corresponding value in the array passes the test specified by predicate. If no objects in the array pass the test, returns NSNotFound.

Discussion of [NSArray indexOfObjectPassingTest]
If the Block parameter is nil this method will raise an exception.

NSArray indexOfObjectPassingTest example.
NSString *keyword = /* whatever */;
NSArray *array = self.myAppointment.OBSERVATIONS;
NSUInteger idx = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    Observations *obs = (Observations*)obj;
    return [obs.TIME  isEqualToString:keyword];
if (idx != NSNotFound)
    Observations *obs = [array objectAtIndex:idx];

Example of [NSArray indexOfObjectPassingTest].
- (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
    return [array indexOfObjectPassingTest:
        ^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
            return [[dictionary objectForKey: @"Name"] isEqualToString: name];

NSArray indexOfObjectPassingTest example.
    CASCategory *cat1 = [[CASCategory alloc] init];
    [cat1 setCategoryTitle:@"foo"];
    CASCategory *cat2 = [[CASCategory alloc] init];
    [cat2 setCategoryTitle:@"bar"];
    CASCategory *cat3 = [[CASCategory alloc] init];
    [cat3 setCategoryTitle:@"baz"];

    NSMutableArray *array = [NSMutableArray arrayWithObjects:cat1, cat2, cat3, nil];
    [cat1 release];
    [cat2 release];
    [cat3 release];

    NSUInteger barIndex = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if ([[(CASCategory *)obj categoryTitle] isEqualToString:@"bar"]) {
            *stop = YES;
            return YES;
        return NO;

    if (barIndex != NSNotFound) {
        NSLog(@"The title of category at index %lu is %@", barIndex, [[array objectAtIndex:barIndex] categoryTitle]);
    else {
        NSLog(@"Not found");

End of NSArray indexOfObjectPassingTest example article.