NSArray *keys = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary * obj2) {
return [obj1[@"weight"] compare:obj2[@"weight"]];
}];
NSLog([keys description]);
Sorting NSDictionary keys by NSNumber value
-
13-07-2023 - |
题
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.
解决方案
其他提示
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"]];
}];
不隶属于 StackOverflow