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.
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;
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.
Here's a one-liner.
NSArray *sortedArray = [unsortedArray sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey@"rating" ascending:NO], [NSSortDescriptor sortDescriptorWithKey@"date" ascending:NO], nil]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With