按键排序的 NSDictionary 实例的快速枚举 [英] fast enumeration for NSDictionary instance ordered by the key
本文介绍了按键排序的 NSDictionary 实例的快速枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我正在使用快速枚举来遍历 NSDictionary 实例
- 我希望根据键的升序枚举 NSDictionary 实例,但事实并非如此
- 我希望能够使用快速枚举按键的升序遍历 NSDictionary 实例
注意:请查看预期输出与实际输出
Note: Pls see expected output vs actual output
- 我的实施是否有误?
- NSDictionary 的快速枚举是否保证基于键的排序?
- 如果没有,那么是否有解决方法并使用快速枚举?
示例
#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
推荐答案
- 没有你的实现是正确的.
- NSDictionary 快速枚举不保证排序(并且由于实现为散列容器,它不会按顺序输出任何内容).
- 不,您必须自己排序.
这篇关于按键排序的 NSDictionary 实例的快速枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文