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

Ala*_*dir 11 iphone objective-c nsmutabledictionary

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

tob*_*yer 19

根据定义,字典未排序.

要按特定顺序迭代键,可以对包含字典键的数组进行排序.

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];
Run Code Online (Sandbox Code Playgroud)

还有其他几种sorted...方法,例如用a排序NSComparator.看看这里.


Ron*_*Ron 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];
}
Run Code Online (Sandbox Code Playgroud)