Objective-C字典是有序容器吗? [英] Is the Objective-C dictionary an ordered container?
问题描述
作为标题,当我将元素插入到目标c中的字典中(顺序如下:k1,k2,k3),是否有任何保证,当我枚举如下:
for(k in dictionary){
/ pre>
//输出k值
}
它会以相同的顺序显示?
解决方案不,
NSDictionary
不保留其键的插入顺序。
如果您需要一个维护插入顺序的字典我建议使用 CHDataStructures框架,它有一个
CHOrderedDictionary
class(它是NSMutableDictionary
的后代)。CHOrderedDictionary
的文档说:
列出顺序中的键的字典它们被插入。
提供以下附加操作以利用以下顺序:
-firstKey
-lastKey
-keyAtIndex:
-reverseKeyEnumerator
键值条目插入正常字典中,包括替换现有键的值,如-setObject:forKey:所详述。但是,并行使用一个额外的结构来跟踪插入顺序,并按顺序枚举密钥。如果要添加的密钥目前不存在于字典中,则将其添加到列表的末尾,否则键的插入顺序不会更改。
as the title, when I insert element to a dictionary in objective-c (in order like: k1, k2, k3), is there any guarantee that when I enumerate it like:
for ( k in dictionary ){ // output the k - value }
it would show in the same order?
解决方案No,
NSDictionary
does not maintain the insertion order of its keys.If you need a dictionary that maintains insertion order, I'd suggest using the CHDataStructures framework, which has a
CHOrderedDictionary
class (it's a descendent ofNSMutableDictionary
). The documentation forCHOrderedDictionary
says:A dictionary which enumerates keys in the order in which they are inserted.
The following additional operations are provided to take advantage of the ordering:
-firstKey
-lastKey
-keyAtIndex:
-reverseKeyEnumerator
Key-value entries are inserted just as in a normal dictionary, including replacement of values for existing keys, as detailed in -setObject:forKey:. However, an additional structure is used in parallel to track insertion order, and keys are enumerated in that order. If a key to be added does not currently exist in the dictionary, it is added to the end of the list, otherwise the insertion order of the key does not change.
这篇关于Objective-C字典是有序容器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!