使用NSSortDescriptor对NSDictionary对象的NSArray进行排序 [英] Sort NSArray of NSDictionary objects using NSSortDescriptor

查看:113
本文介绍了使用NSSortDescriptor对NSDictionary对象的NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列词典,其中包含有关高分的信息.我试图找出如何按照字典中的不同值对它们进行排序,但无法使其正常工作.

I have an array of dictionaries that contain information about high scores. I am trying to figure out how to sort them by the different values in the dictionaries but cannot get it to work.

下面显示的示例尝试按分数"进行排序:

An example shown below attempts to sort by "Score":

NSDictionary *highScoreDictionary1 = @{@"Score" : @52, @"Duration" : @230 , @"Date" : [NSDate date]};
NSDictionary *highScoreDictionary2 =  @{@"Score" : @23, @"Duration" : @230 , @"Date" : [NSDate date]};
NSDictionary *highScoreDictionary3 = @{@"Score" : @35, @"Duration" : @230 , @"Date" : [NSDate date]};

NSArray *highScoresArray = @[highScoreDictionary1, highScoreDictionary2, highScoreDictionary3];

NSSortDescriptor *highScoreSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Score" ascending:YES];  // Sort by Score
NSArray *sortDescriptorArray = [NSArray arrayWithObject:highScoreSortDescriptor];

[highScoresArray sortedArrayUsingDescriptors:sortDescriptorArray];

我从NSLog(@"sorted array of dictionaries: %@", highScoresArray);获得的输出是:

sorted array of dictionaries: (
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 52;
    },
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 23;
    },
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 35;
    }
)

我该如何补救?我是否在这里遗漏了某些东西,因为似乎字典没有按分数排序?

How do I remedy this? Am I missing something here because it seems that the dictionaries are not being sorted by score.

推荐答案

highScoresArray = [highScoresArray sortedArrayUsingDescriptors:sortDescriptorArray];

这篇关于使用NSSortDescriptor对NSDictionary对象的NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆