假设我有一个包含键(单词)和值(分数)的字典,如下所示:
GOD 8
DONG 16
DOG 8
XI 21
我想创建一个字典键(单词)的 NSArray,它首先按分数排序,然后按字母顺序排序。从上面的示例中,这将是:
XI
DONG
DOG
GOD
实现这一目标的最佳方法是什么?
假设我有一个包含键(单词)和值(分数)的字典,如下所示:
GOD 8
DONG 16
DOG 8
XI 21
我想创建一个字典键(单词)的 NSArray,它首先按分数排序,然后按字母顺序排序。从上面的示例中,这将是:
XI
DONG
DOG
GOD
实现这一目标的最佳方法是什么?
我会使用 NSDictionaries 和 NSArray,然后使用 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]];
卡洛斯的回答是正确的,我只是发布了我最终得到的完整代码,以防万一有人感兴趣:
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);
我无法对此进行测试,因为我不在 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"]);
这会做同样的事情,但会有所减少并避免迭代。