如何用键值对NSMutableDictionary进行排序?

时间:2011-11-14 08:23:59

标签: iphone objective-c nsmutabledictionary

我有一个带有字符串键的NSMutableDictionary,每个键都有自己的数组。我想按字母顺序用键值重新排序字典。我怎么能这样做?

3 个答案:

答案 0 :(得分:19)

根据定义,字典未排序。

为了按特定顺序迭代键,您可以对包含字典键的数组进行排序。

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];

还有其他几种sorted...方法,例如用NSComparator排序。看看here

答案 1 :(得分:8)

使用此

NSArray *myKeys = [Dict allKeys];
NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSMutableArray *sortedValues = [[[NSMutableArray alloc] init] autorelease];

for(id key in sortedKeys) {
    id object = [Dict objectForKey:key];
    [sortedValues addObject:object];
}

答案 2 :(得分:2)

NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];