Apple should make a method that returns an array's object that satisfies a predicate.

Discussion in 'iOS Programming' started by moonman239, Nov 19, 2013.

  1. moonman239 macrumors 68000

    Joined:
    Mar 27, 2009
    #1
    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];
    
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    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:.
     
  3. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    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).
     
  4. Duncan C macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #4
    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.
     
  5. MattInOz macrumors 68030

    MattInOz

    Joined:
    Jan 19, 2006
    Location:
    Sydney
    #5
    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.
     
  6. Duncan C macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #6
    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.
     

Share This Page