Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

moonman239

Cancelled
Original poster
Mar 27, 2009
1,541
32
I looked at the indexOfObjectPassingTest method that comes with all NSArrays. I actually had to dig up some documentation that gave me the code. It would be nice if all I had to do was something like this:

Code:
NSPredicate *predicate = // predicate code here
NSInteger *indexOfObjectThatSatisfiesPredicate = [array indexOfObjectThatSatisfiesPredicate:predicate];
 
You can write your own category on the NSArray class that returns either the first object satisfying the predicate, or nil if no objects satisfy the predicate.

There's also the NSArray method filteredArrayUsingPredicate:.
 
Code:
NSInteger *indexOfObjectThatSatisfiesPredicate = [array indexOfObjectThatSatisfiesPredicate:predicate];

Just wanted to point out that you probably don't want an "NSInteger *" return value. NSInteger (without the pointer) would suffice, as it's a Foundation Data Type (which is typedef'd long).
 
You can write your own category on the NSArray class that returns either the first object satisfying the predicate, or nil if no objects satisfy the predicate.

There's also the NSArray method filteredArrayUsingPredicate:.

Indeed, you could write this with just a few lines of code:

Code:
NSPredicate *predicate = //create a predicate
NSArray *resultsArray =[myArray filteredArrayUsingPredicate: predicate];
id result = nil;
if ([resultsArray count] >0)
  result = resultsArray[0];

And turning that into a category method on NSArray would be trivial.
 
Couldn't you just do....

Code:
NSPredicate *predicate = //create a predicate
id result =[[myArray filteredArrayUsingPredicate: predicate] firstObject];

Well assuming your using the most up to date SDK as -firstObject as only added recently, and some old runtimes error if message nil.
 
Couldn't you just do....

Code:
NSPredicate *predicate = //create a predicate
id result =[[myArray filteredArrayUsingPredicate: predicate] firstObject];

Well assuming your using the most up to date SDK as -firstObject as only added recently, and some old runtimes error if message nil.

According to the docs firstObject was added in iOS 4.0. Given that Xcode 5 only supports iOS >= 4.3, using it is probably safe. (We gave up on iOS 4.x for new development over a year ago - almost 2 years ago, if memory serves.)

Sending a message to a nil object is legal in every implementation of Objective C. It's part of the language spec.

And it looks like firstObject cleanly returns nil if the array is empty, so that is simpler, more elegant solution than mine.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.