Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting multiple sort descriptors

I have a array of objects and need to sort it by rating and after by number of votes descendent(so that if two 5 stars rated elements compare, the one with the most votes should be first)

Is it possible to sort a NSArray by two descriptors:first after rating and then after votes count?

I've found on http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html

something like sortUsingDescriptors: but i can't find it anywhere in the docs, think it's deprecated.

like image 809
Alex Avatar asked Sep 20 '11 09:09

Alex


3 Answers

Yes you can:

NSSortDescriptor *sortRating = [[NSSortDescriptor alloc] initWithKey:@"rating" ascending:NO];
NSSortDescriptor *sortVotes = [[NSSortDescriptor alloc] initWithKey:@"votes" ascending:NO];

NSArray *sortedArray = [orignalAray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortRating, sortVotes, nil]];
[sortRating release], sortRating = nil;
[sortVotes release], sortVotes = nil;
like image 184
rckoenes Avatar answered Dec 01 '22 15:12

rckoenes


You are basically right. On NSArray there is the

- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors 

method. This will return a new array, sorted according to various descriptors.

- (void)sortUsingDescriptors:(NSArray *)sortDescriptors

does exist, but is on NSMutableArray, which might explain why you couldn't find it in the documentation for NSArray. It accomplishes the same goal, but sorts the array you call it on, rather than returning a new array. Neither is deprecated.

like image 38
Matthew Gillingham Avatar answered Dec 01 '22 15:12

Matthew Gillingham


Here's a one-liner.

NSArray *sortedArray = [unsortedArray sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey@"rating" ascending:NO], [NSSortDescriptor sortDescriptorWithKey@"date" ascending:NO], nil]];
like image 22
Phil Avatar answered Dec 01 '22 15:12

Phil