문제

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.

도움이 되었습니까?

해결책

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

NSLog([keys description]);

다른 팁

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"]];
}];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top