gpt4 book ai didi

cocoa - 有序 NSDictionary

转载 作者:行者123 更新时间:2023-12-03 16:11:39 26 4
gpt4 key购买 nike

如何保留向 NSDictionary 添加对象的方式?

我意识到 NSDictionary 中的值没有特定的顺序,但就我而言,我需要保留使用 setValue:forKey: 添加的顺序,例如一个数组。

我怎样才能做到这一点?

感谢任何帮助。

最佳答案

字典经过 HashMap 以加快检索速度。您无权修改其顺序。

如果你想按顺序存储,你应该使用数组。

或者你必须使用一些复杂的方法,继续用键附加一个int orderNumber(你需要在每次setObject/setValue之后递增它)。存储和检索为:

NSDictionary *dict=[NSDictionary new];
NSString *key=....;
[dict setValue:@"some value" forKey:[NSString stringWithFormat:@"%d-%@",orderNumber, key]];
<小时/>

或者,您可以使用每个索引有一个字典的数组。

<小时/>

另一种方法是使用自定义类

@interface ....
@property(...) NSInteger index;
@property(...) NSString *key;
@property(...) id object;
// and methods to retrieve based on key, based on index etc
@end

编辑2:

发现与我一年前发布的内容非常相似,请参阅此OrderedDictionary .

关于cocoa - 有序 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500628/

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