按键排序的NSDictionary实例的快速枚举

use*_*037 4 objective-c nsdictionary fast-enumeration

概观

  • 我正在使用快速枚举来遍历NSDictionary实例
  • 我希望根据密钥的升序来枚举NSDictionary实例,但似乎并非如此

我想做的事:

  • 我希望能够使用快速枚举以密钥的升序迭代NSDictionary实例

注意:请参阅预期输出与实际输出

问题

  1. 我的实施错误了吗?
  2. NSDictionary的快速枚举是否保证基于密钥的排序?
  3. 如果没有,那么有没有解决这个问题,但使用快速枚举?

#import<Foundation/Foundation.h>

int main()
{
    system("clear");

    NSDictionary *d1 = nil;

    @autoreleasepool
    {   

        d1 = [[NSDictionary alloc] initWithObjectsAndKeys: @"AAA", [NSNumber numberWithInt:10], 
              @"BBB", [NSNumber numberWithInt:20],               
              @"CCC", [NSNumber numberWithInt:30],               
              nil];
    }   

    for(NSNumber* n1 in d1)     //I expected fast enumeration for NSDictionary to be based on the 
        //ascending order of the key but that doesn't seem to be the case
    {
        printf("key = %p"
               "\t [key intValue] = %i"
               "\t value = %s\n", 
               n1, 
               [n1 intValue], 
               [[d1 objectForKey:n1] UTF8String]);
    }   

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

预期产出

key = 0xa83      [key intValue] = 10     value = AAA
key = 0x1483     [key intValue] = 20     value = BBB
key = 0x1e83     [key intValue] = 30     value = CCC
Run Code Online (Sandbox Code Playgroud)

实际产出

key = 0x1e83     [key intValue] = 30     value = CCC
key = 0xa83      [key intValue] = 10     value = AAA
key = 0x1483     [key intValue] = 20     value = BBB
Run Code Online (Sandbox Code Playgroud)

NSR*_*der 13

for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
    id value = [d1 valueForKey:key];
    ...
}
Run Code Online (Sandbox Code Playgroud)