iOS: Sorted Array with Compare

Question(提问):

What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, let's say they are 'Person' objects. I want to sort the NSMutableArrayby Person.birthDate which is an NSDate.

I think it has something to do with this method:

NSArray*sortedArray =[drinkDetails sortedArrayUsingSelector:@selector(???)];

In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?

Anwser(回答):

Compare method

Either you implement a compare-method for your object:

-(NSComparisonResult)compare:(Person*)otherObject {
    return[self.birthDate compare:otherObject.birthDate];
}

NSArray*sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)

or usually even better:

NSSortDescriptor*sortDescriptor;
sortDescriptor =[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES];NSArray*sortDescriptors =[NSArray arrayWithObject:sortDescriptor];NSArray*sortedArray;
sortedArray =[drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

Blocks (shiny!)

There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

NSArray*sortedArray;
sortedArray =[drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b){
    NSDate*first = [(Person*)a birthDate];
    NSDate*second =[(Person*)b birthDate];
    return [first compare:second];
}];

转自:http://stackoverflow.com/a/805589(Stack Overflow) 

原文地址:https://www.cnblogs.com/ihojin/p/ios-sort-with-compare.html