Help sorting an NSArray across two properties (with NSSortDescriptor?)
cocoa, nsarray, nssortdescriptor, sorting
Solution
The `sortedArrayUsingDescriptors:` `NSArray` method does most of what you need:
The first descriptor specifies the primary key path to be used in sorting the receiver’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.
Some filtering with `NSPredicate` is required too:
NSSortDescriptor *timeSD = [NSSortDescriptor sortDescriptorWithKey: @"time" ascending: YES];
NSMutableArray *sortedByTime = [UnsortedArray sortedArrayUsingDescriptors: timeSD];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:[sortedByTime count]];
while([sortedByTime count])
{
id groupLead = [sortedByTime objectAtIndex:0];
NSPredicate *groupPredicate = [NSPredicate predicateWithFormat:@"name = %@", [groupLead name]];
NSArray *group = [sortedByTime filteredArrayUsingPredicate: groupPredicate];
[sortedArray addObjectsFromArray:group];
[sortedByTime removeObjectsInArray:group];
}
I have no idea if this is the most efficient method, but until you have reason to believe that it is causing problems there's no need to worry the performance implications. It's premature optimisation. I wouldn't have any concerns about the performance of this method. You've got to trust the framework otherwise you'll end up rewriting it (thus undermine the point of the framework) due to an unfounded paranoia.
Problem
I'm a bit of a NSSortDescriptor n00b. I think, though, it is the right tool for what I need to do: I have an NSArray consisting of objects with keys, say, "name" and "time". Instead of verbalizing it, here's an example: ``` input: name: time B: 4 C: 8 B: 5 C: 4 A: 3 C: 2 A: 1 A: 7 B: 6 desired output: name: time A: 1 <--- A: 3 A: 7 C: 2 <--- C: 4 C: 8 B: 4 <--- B: 5 B: 6 ``` So the values are sorted by "time" and grouped by "name". A comes first because he had the smallest time value, and all values for A come after one another. Then comes C, he had the second smallest time value out of all his values. I have indicated the values that determine how the names are sorted; within each name group, sorting is by time. How do I get from input to output NSArray in the most efficient way? (cpu- and memory-wise, not necessarily code-wise.) How would I construct the NSSortDescriptors for this, or use any other method? I don't want to roll my own unless it's the most efficient way.