在 Objective-C 中,我能否按键对 NSDictionary 进行排序?

45

我可以按照键名对NSDictionary进行排序吗?


1
答案是否为您提供了正确的信息?也许您可以将其标记为答案,这样问题就会被标记为已解决。 - Alex Cio
2个回答

116
你可以对键进行排序,然后通过迭代创建一个NSMutableArray
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
    [sortedValues addObject: [dict objectForKey: key]];

4
这是一个正确的答案吗?得到了很多投票,但没有被采纳吗? - Just a coder
3
你提到的方法已经有些过时。但是大声朗读一下:“按值排序的键”,这个方法会在使用选择器对值对象进行排序时返回字典的键。它不会返回按照该选择器排序的键,而这正是上述代码所做的。 - Max Seelemann
@mikeho:我能理解你的想法。然而,这将是非常不一致的命名方式,不符合苹果框架标准。虽然我意识到该方法应该被称为keysSortedByObjectUsingSelector: - Max Seelemann
@MaxSeelemann:是的,我认为更多的是似乎缺少一个简单的API来返回排序后的键,所以这让我感到困惑。NSDictionary应该有一个名为keysSortedUsingSelector:的API,以使事情更加清晰。 - mikeho
4
You can't sort a NSDictionary but you can use an NSArray to store the keys in a specific order, and then access the values from the NSDictionary based on the sorted keys. Alternatively, you can create an array of the NSDictionary's values and sort that using one of the sorting methods available for NSArrays. - Pierre de LESPINAY
显示剩余2条评论

7

使用objectsForKeys:notFoundMarker:要简单得多。

NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
// As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接