【问题标题】:fast enumeration for NSDictionary instance ordered by the key按键排序的 NSDictionary 实例的快速枚举
【发布时间】:2011-12-16 04:09:02
【问题描述】:

概述

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

【问题讨论】:

标签: objective-c nsdictionary fast-enumeration


【解决方案1】:
for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
    id value = [d1 valueForKey:key];
    ...
}

【讨论】:

  • 但是,虽然这对结果排序的键数组使用了快速枚举,但它没有在字典上使用快速枚举,这是 OP 说他想做的......
  • 感谢 NSResponder 和 Matt 的回复,这是一个很好的解决方法。
【解决方案2】:
  1. 不,你的实现是正确的。
  2. NSDictionary 快速枚举不保证排序(并且由于实现为散列容器,它不会按顺序输出任何内容)。
  3. 不,您必须自己排序。

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 谢谢文斯,这是一个很好的建议。我想如果键的顺序比值的顺序更重要,那么我可能可以创建字典,将键作为我的值,我的值作为我的键。然后使用方法keysSortedByValueUsingSelector:
    • @user1046037 它始终取决于您的目标是什么以及您需要什么。数组擅长使事物井井有条,因此根据具体情况,您可能会考虑将一些自定义类保存在数组中并根据其属性之一进行排序。我只是在抛出想法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多