How do I sort an NSMutableArray with custom objects in it?

前端 未结 27 3914
予麋鹿
予麋鹿 2020-11-21 04:45

What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray of objects, and let\'s say they are \'Person\' objects

27条回答
  •  孤城傲影
    2020-11-21 05:12

    See the NSMutableArray method sortUsingFunction:context:

    You will need to set up a compare function which takes two objects (of type Person, since you are comparing two Person objects) and a context parameter.

    The two objects are just instances of Person. The third object is a string, e.g. @"birthDate".

    This function returns an NSComparisonResult: It returns NSOrderedAscending if PersonA.birthDate < PersonB.birthDate. It will return NSOrderedDescending if PersonA.birthDate > PersonB.birthDate. Finally, it will return NSOrderedSame if PersonA.birthDate == PersonB.birthDate.

    This is rough pseudocode; you will need to flesh out what it means for one date to be "less", "more" or "equal" to another date (such as comparing seconds-since-epoch etc.):

    NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
      if ([firstPerson birthDate] < [secondPerson birthDate])
        return NSOrderedAscending;
      else if ([firstPerson birthDate] > [secondPerson birthDate])
        return NSOrderedDescending;
      else 
        return NSOrderedSame;
    }
    

    If you want something more compact, you can use ternary operators:

    NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
      return ([firstPerson birthDate] < [secondPerson birthDate]) ? NSOrderedAscending : ([firstPerson birthDate] > [secondPerson birthDate]) ? NSOrderedDescending : NSOrderedSame;
    }
    

    Inlining could perhaps speed this up a little, if you do this a lot.

提交回复
热议问题