4

概述

  • 我正在使用快速枚举来遍历 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);
}

预期产出

key = 0xa83      [key intValue] = 10     value = AAA
key = 0x1483     [key intValue] = 20     value = BBB
key = 0x1e83     [key intValue] = 30     value = CCC

实际输出

key = 0x1e83     [key intValue] = 30     value = CCC
key = 0xa83      [key intValue] = 10     value = AAA
key = 0x1483     [key intValue] = 20     value = BBB
4

3 回答 3

13
for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
    id value = [d1 valueForKey:key];
    ...
}
于 2011-12-16T04:24:04.053 回答
2
  1. 不,您的实现是正确的。
  2. NSDictionary 快速枚举不保证排序(并且由于实现为散列容器,它不会按顺序输出任何内容)。
  3. 不,你必须自己整理。
于 2011-12-16T04:21:58.010 回答
1

对于您收到物品的顺序没有任何保证。

allKeys
返回一个包含字典键的新数组。
- (NSArray *)allKeys
返回值
包含字典键的新数组,如果字典没有条目,则为空数组。
讨论
未定义数组中元素的顺序

所以我的建议是,如果您的字典不经常更改,NSArray请按照您想要的顺序缓存一个键。
如果您的字典经常更改,您可能需要allKeys在需要时对其进行排序。

于 2011-12-16T04:23:09.100 回答