Reputation: 6132
I've got an array of NSMutableDictionaries, containing (amongst others) the key Location. I need to sort the array to input it into a table. On top should be N, below should be A, and below that should be R. So in sort: How can I sort an array in the order: N - A - R?
EDIT: I can order by looking at two variables, but I'm using more then 2 variables (7 in total)...
Thanks,
Upvotes: 5
Views: 4071
Reputation: 125007
If your array is mutable, you can sort it using the -sortUsing... methods. If not, you can create a new, sorted array using the -sortedArrayUsing... methods. For example, there are -sortUsingComparator: and -sortedArrayUsingComparator: methods which take a comparator block as a parameter. You just need to supply a block that compares two objects using your custom sort order, like this:
[myArray sortUsingComparator:^(id firstObject, id secondObject) {
NSString *firstKey = [firstObject valueForKey:@"location"];
NSString *secondKey = [secondObject valueForKey:@"location"];
if ([firstKey stringEqual:@"N"] || [lastKey stringEqual:@"R"])
return NSOrderedAscending;
else if ([firstKey stringEqual:secondKey])
return NSOrderedSame;
else
return NSOrderedDescending;
}];
There's a pretty thorough discussion of sorting arrays, with examples, in the Collections Programming Topics document.
Upvotes: 6