概述
- 我正在使用快速枚举来遍历 NSDictionary 实例
- 我希望根据键的升序枚举 NSDictionary 实例,但似乎并非如此
我想做的事:
- 我希望能够使用快速枚举以键的升序遍历 NSDictionary 实例
注意:请查看预期输出与实际输出
问题
- 我的实施有误吗?
- 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