注意:请参阅预期输出与实际输出
#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
答案 0 :(得分:13)
for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
id value = [d1 valueForKey:key];
...
}
答案 1 :(得分:2)
答案 2 :(得分:1)
对于您收到对象的顺序没有任何保证。
allKeys
返回包含字典键的新数组 - (NSArray *)allKeys
返回值
包含字典键的新数组,如果字典没有条目,则为空数组 讨论
未定义数组中元素的顺序。
所以我的建议是,如果您的词典没有经常更改,请按照您希望的顺序缓存NSArray
密钥。
如果您的词典经常更改,则可能需要在需要时对allKeys
进行排序。