Domanda

I have some NSDictionary like this:

@{
@"some key":{
    @"notImportantKey":@"asdasda",
    @"weight":@1
},
@"some key 2":{
    @"notImportantKey":@"asdasda",
    @"weight":@2
},
@"some key 3":{
    @"notImportantKey":@"asdasda",
    @"weight":@3
},
@"some key 4":{
    @"notImportantKey":@"asdasda",
    @"weight":@4
}}

I need array of keys (some key, some key2,...), sorted by weight value.

È stato utile?

Soluzione

NSArray *keys = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary * obj2) {
    return [obj1[@"weight"] compare:obj2[@"weight"]];
}];

NSLog([keys description]);

Altri suggerimenti

This is what keysSortedByValueUsingComparator: is for. It compares the values at the dictionary and gives you the order the keys would be in if they were sorted using those values. For example:

[yourDictionary keysSortedByValueUsingComparator:^(NSDictionary *a, NSDictionary *b) {
    return [a[@"weight"] compare:b[@"weight"]];
}];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top