I have an NSMutableArray with my Person objects, I want to sort this array by Person.birthDate of type NSDate . It should probably be something like this:

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

    1 answer 1

    Compare method

    Also create a comparison method for your object:

     - (NSComparisonResult)compare:(Person *)otherObject { return [self.birthDate compare:otherObject.birthDate]; } NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)]; 

    NSSortDescriptor (preferred method)

    Often the preferred option is to use descriptors:

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

    You can sort by multiple keys simply by adding additional descriptors to the array. It is also possible to use your own comparison methods. Take a look at the documentation .

    Blocks (brilliant way)

    On Mac OS X 10.6 and iOS 4 and higher, you can sort using blocks:

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

    Performance

    Using -compare: and blocks generally works somewhat faster than the descriptor array description, since they use Key-Value-Coding . The main advantage of NSSortDescriptor is that it allows you to determine the sort order by describing more data than the code. This makes it quite easy for the user to choose the sort order, for example, by clicking on the column headers in the NSTableView .

    Translation of the answer: How to sort an NSMutableArray with custom objects in it?