GeneCode GeneCode -4 years ago 114
Objective-C Question

Sort dictionary by multiple keys

I have myDict in the format of:

{
data1 = {
key1 = abc
key2 = abc
key3 = abc
key4 = abc
},
data2 = {
key1 = abc
key2 = abc
key3 = abc
key4 = abc
}
..
}


I use the following code to sort myDict and get the the sorted data by keys.

sortedArr = [myDict keysSortedByValueUsingComparator:
^NSComparisonResult(NSDictionary* obj1, NSDictionary* obj2)
{
NSComparisonResult result = NSOrderedSame;
if(obj1[@"key1"] != nil && obj2[@"key1"]!=nil)
{
return [obj2[@"key1"] compare:obj1[@"key1"]];
}
else
return result;
}];


sortedArr:

(data1,data2,data3,...)


question is how do i sort myDict using 2 keys instead of one because I face an issue if key1 value are the same, then i want it to be sorted by key2.

Answer Source

You just need to account for the case for each key where the comparison returns NSOrderedSame. You can iterate the keys like this:

NSArray *allKeys = @[@"key1", @"key2", @"key3", ...];
for (NSString *aKey in allKeys)
{
    if(obj1[aKey] != nil && obj2[aKey] != nil)
    {
        NSComparisonResult result = [obj2[aKey] compare:obj1[aKey]]; 
        if (result != NSOrderedSame) return result;
    }
}
return NSOrderedSame;

This answer is substantially different from my original answer, all credit to Larme for this solution

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download