Mr.G Mr.G - 2 months ago 8
iOS Question

Sort mutable dictionary based on values of it

I have an unordered NSMutableDictioanry and this dictioanry is created as in following example

{
1 = 27;
2 = 5;
3 = 13964;
4 = 2422;
5 = 45;
6 = 7;
7 = 27;
8 = 39;
}


i want to sort this dictionary based on values. And this can be done according to following article and it works perfectly fine Getting NSDictionary keys sorted by their respective values and will returns an array with keys sorted based on values

(
2,
6,
7,
1,
8,
5,
4,
3
)


So my question is there anyway that i can get a sorted dictionary directly instead of array

Answer

As a non-parallel object solution, you could use an array to store the key-value pairs as an array of two items. keyValuePair[0] is the key and keyValuePair[1] is the value.

- (NSArray *)sortedDataFromDictionary:(NSDictionary *)dictionary {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:dictionary.count];

    for (NSNumber *key in [dictionary keysSortedByValueUsingSelector:@selector(compare:)]) {
        NSArray *keyValuePair = @[key, dictionary[key]];
        [result addObject:keyValuePair];
    }

    return [result copy];
}

Early on, when the dictionary has been set (maybe in -viewWillAppear:).

self.sortedData = [self sortedDataFromDictionary:dictionary];

Then in -tableView:cellForRowAtIndexPath: use

NSNumber *key = self.sortedData[indexPath.row][0];
NSNumber *value = self.sortedData[indexPath.row][1];