gpt4 book ai didi

objective-c - 按键排序的 NSDictionary 实例的快速枚举

转载 作者:太空狗 更新时间:2023-10-30 03:56:47 25 4
gpt4 key购买 nike

概览

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

最佳答案

for (NSString *key in [[d1 allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
id value = [d1 valueForKey:key];
...
}

关于objective-c - 按键排序的 NSDictionary 实例的快速枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8529660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com