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?
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:I've also seen this one when searching for this: http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html
NSDictionary's keys aren't kept in order, but you can get them and sort them, E. G:
No, it is not ordered. You can use an array of keys to remember an order if you need to, but dictionaries are conceptually unordered bags of key-value pairs.
Something I'd like to add in case someone is searching for this and stumbles on this thread:
There's a rather easy work-around for ordered dictionaries, and that's having an Array, which contains the keys in the order you want. Then having an unordered dictionary, but you can access each key in order using the keys from the array: