我可以根据Objective-C中的键对NSDictionary进行排序吗?

时间:2010-08-27 09:50:32

标签: objective-c sorting key nsdictionary

我可以根据密钥对NSDictionary进行排序吗?

2 个答案:

答案 0 :(得分:114)

您可以对键进行排序,然后通过迭代来创建NSMutableArray

NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
    [sortedValues addObject: [dict objectForKey: key]];

答案 1 :(得分:1)

使用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:@""];