获取NSAroray的NSDictionary键,按Value然后键排序

时间:2012-09-24 18:19:37

标签: objective-c cocoa-touch cocoa nsdictionary nssortdescriptor

假设我有一个包含键(单词)和值(分数)的字典,如下所示:

GOD    8
DONG   16
DOG    8
XI     21

我想创建一个字典键(单词)的NSArray,首先按分数排序,然后按字母顺序排序。从上面的例子可以看出:

XI
DONG
DOG
GOD

实现这一目标的最佳方式是什么?

3 个答案:

答案 0 :(得分:1)

我会使用NSArray和NSDrray,然后使用NSSortDescriptors实现它:

NSSortDescriptor *sdScore = [NSSortDescriptor alloc] initWithKey:@"SCORE" ascending:NO];
NSSortDescriptor *sdName = [NSSortDescriptor alloc] initWithKey:@"NAME" ascending:YES];
NSArray *sortedArrayOfDic = [unsortedArrayOfDic sortedArrayUsingDescriptors:[NSArray arrayWithObjects: sdScore, sdName, nil]];

答案 1 :(得分:0)

Carlos的答案是正确的,我只是发布完整的代码,以防万一有人感兴趣:

NSDictionary *dataSourceDict = [NSDictionary dictionaryWithObjectsAndKeys:
                      [NSNumber numberWithInt:8], @"GOD",
                      [NSNumber numberWithInt:16], @"DONG",
                      [NSNumber numberWithInt:8], @"DOG",
                      [NSNumber numberWithInt:21], @"XI", nil];

NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:@"SCORE" ascending:NO];
NSSortDescriptor *wordSort = [NSSortDescriptor sortDescriptorWithKey:@"WORD" ascending:YES];
NSArray *sorts = [NSArray arrayWithObjects:scoreSort, wordSort, nil];


NSMutableArray *unsortedArrayOfDict = [NSMutableArray array];

for (NSString *word in dataSourceDict)
{
    NSString *score = [dataSourceDict objectForKey:word];
    [unsortedArrayOfDict addObject: [NSDictionary dictionaryWithObjectsAndKeys:word, @"WORD", score, @"SCORE",  nil]];
}
NSArray *sortedArrayOfDict = [unsortedArrayOfDict sortedArrayUsingDescriptors:sorts];

NSDictionary *sortedDict = [sortedArrayOfDict valueForKeyPath:@"WORD"];

NSLog(@"%@", sortedDict);

相关:NSDictionary split into two arrays (objects and keys) and then sorted both by the objects array (or a similar solution)

答案 2 :(得分:0)

我无法测试这个,因为我不在Mac上(对不起,如果我拼错了一些东西),但是:

NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"GOD", @"WORD", [NSNumber numberWithInt:8], @"SCORE", nil];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"DONG", @"WORD", [NSNumber numberWithInt:16], @"SCORE", nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"DOG", @"WORD", [NSNumber numberWithInt:8], @"SCORE", nil];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"XI", @"WORD", [NSNumber numberWithInt:21], @"SCORE", nil];

NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:@"SCORE" ascending:NO];
NSSortDescriptor *wordSort = [NSSortDescriptor sortDescriptorWithKey:@"WORD" ascending:YES];

NSArray *sortedArrayOfDic = [[NSArray arrayWithObjects:dic1, dic2, dic3, dic4, nil] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:scoreSort, wordSort, nil]];

NSLog(@"%@", [sortedArrayOfDict valueForKeyPath:@"WORD"]);

这会做同样的事情,但有点减少并避免迭代。