Search code examples
iphoneiosios4nsdictionarynssortdescriptor

Sorting of NSDictionary by amount of children per key


After searching the developer docs, google and other sites I still can't find how to accomplish the following...

I would like to sort a NSDictionary by the amount of values (i.e. count) per key. Do I need to use a custom NSSortDescriptor and if so, I would really appreciate some help with the code. Below is an example of the NSDictionary I would like sorted.

2 ways I would like to be able to sort dictionary:

1) Sort it so that the key "Australia" comes first because it has 3 cities, then USA with 2 cities, and finally UK with 1 city?

2) For a bonus I would also love to have the option to sort by the amount of objects i.e. Australia first with 6 objects, then UK with 4 objects (even though only 1 city) then USA with 2 objects.

"United Kingdom" = {
    "City 1" = {
        1 = "Object A";
        2 = "Object B";
        3 = "Object C";
        4 = "Object D";
    };
};
"Australia" = {
    "City 1" = {
        5 = "Object E";
        6 = "Object F";
        7 = "Object G";
    };
    "City 2" = {
        8 = "Object H";
        9 = "Object I";
    };
    "City 3" = {
        10 = "Object J";
    };
};
"United States of America" = {
    "City 1" = {
        11 = "Object K";
    };
    "City 2" = {
        12 = "Object L";
    };
};

Solution

  • Assuming you do store arrays in the dictionary you could do something like this:

    NSComparator sorter = ^NSComparisonResult(id a, id b)
    {
        NSArray* a1 = a;
        NSArray* a2 = b;
        if([a1 count] > [a2 count]) return NSOrderedAscending; 
        if([a1 count] < [a2 count]) return NSOrderedDescending; 
        return NSOrderedSame;
    }
    
    NSArray* ordered = [dictionary keysSortedByValueUsingComparator:sorter];
    

    Then in the "ordered" array you'll get the keys to the dictionary in the order of increasing number of elements in the arrays stored in the dictionary.