首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据字典的值对NSarray排序

如何根据字典的值对NSarray排序
EN

Stack Overflow用户
提问于 2013-07-23 21:09:04
回答 1查看 302关注 0票数 0

我有下面的NSArray,它有一个NSDictionary,我需要对它们进行排序,以便将更高的字典值放在上面。

我已经研究过了,但是我找不到一个谓词来对我的NSDictionary排序。我怎样才能达到我的目标?

代码语言:javascript
复制
 NSArray* result = @[@{ @"chest":[NSString stringWithFormat:@"%i",[chestR count]]},
                      @{@"back":[NSString stringWithFormat:@"%i",[backR count]]},
                      @{@"triceps":[NSString stringWithFormat:@"%i",[tricepR count]]},
                      @{@"biceps":[NSString stringWithFormat:@"%i",[bicepR count]]},
                      @{@"arms-other":[NSString stringWithFormat:@"%i",[armsR count]]},
                      @{@"legs":[NSString stringWithFormat:@"%i",[legsR count]]},
                      @{@"shoulders":[NSString stringWithFormat:@"%i",[shouldersR count]]},
                      @{@"abs":[NSString stringWithFormat:@"%i",[absR count]]},
                      @{@"cardio":[NSString stringWithFormat:@"%i",[cardioR count]]},
                      @{@"fitness":[NSString stringWithFormat:@"%i",[fitnessR count]]}
                        ];

编辑与解决

我就是这样解决问题的

代码语言:javascript
复制
NSArray* result = @[@{ @"chest":@"5"},
                        @{@"back":@"3"},
                        @{@"triceps":@"4"},
                        @{@"biceps":@"9"},
                        @{@"arms-other":@"1"},
                        @{@"legs":@"0"},
                        @{@"shoulders":@"2"},
                        @{@"abs":@"3"},
                        @{@"cardio":@"8"},
                        @{@"fitness":@"9"}
                        ];

    NSArray *sorted = [result sortedArrayUsingComparator:^(id obj1, id obj2){

        NSArray *s1k = [obj1 allKeys];
        NSInteger s1 = [obj1[[s1k objectAtIndex:0]] intValue];
        NSArray *s2k = [obj2 allKeys];
        NSInteger s2 = [obj2[[s2k objectAtIndex:0]] intValue];

        if ( s1 > s2) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if (s1 < s2) {
            return (NSComparisonResult)NSOrderedDescending;
        }

        return (NSComparisonResult)NSOrderedSame;
    }];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-23 21:19:17

字典不是按定义排序的。

您可以将其转换为数组。NSDictionary实例方法-allValues可能适合这样做。

然后,您可以使用自定义排序描述符对新数组进行排序,以确保按您希望的方式对其进行排序。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17821130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档