Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj/C: Sorting an array on a custom order

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,

like image 585
Joetjah Avatar asked Mar 31 '11 08:03

Joetjah


1 Answers

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.

like image 127
Caleb Avatar answered Sep 30 '22 04:09

Caleb