订购NSDictionary

Jac*_*ill 5 cocoa hashtable nsdictionary

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

我意识到没有特定的值顺序NSDictionary,但在我的情况下,我需要保留我添加的顺序setValue:forKey:,如数组.

我怎么能这样做?

任何帮助赞赏.

Ano*_*dya 2

字典是哈希映射的,以便更快地检索。您无权修改其顺序。

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

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

NSDictionary *dict=[NSDictionary new];
NSString *key=....;
[dict setValue:@"some  value" forKey:[NSString stringWithFormat:@"%d-%@",orderNumber, key]];
Run Code Online (Sandbox Code Playgroud)

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


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

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

编辑2:

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