As a rule, I use indexOfObjectPassingTest: since it is more convenient for me to express my test in Objective-C, rather than NSPredicate syntax. Here is a simple example (imagine that integerValue was actually a property):
NSArray *array = @[@0,@1,@2,@3]; NSUInteger indexOfTwo = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { return ([(NSNumber *)obj integerValue] == 2); }]; NSUInteger indexOfFour = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { return ([(NSNumber *)obj integerValue] == 4); }]; BOOL hasTwo = (indexOfTwo != NSNotFound); BOOL hasFour = (indexOfFour != NSNotFound); NSLog(@"hasTwo: %@ (index was %d)", hasTwo ? @"YES" : @"NO", indexOfTwo); NSLog(@"hasFour: %@ (index was %d)", hasFour ? @"YES" : @"NO", indexOfFour);
The output of this code is:
hasTwo: YES (index was 2) hasFour: NO (index was 2147483647)
Carl Veazey Aug 16 '13 at 14:25 2013-08-16 14:25
source share