Reputation:
I mean: Is the order of keys and values in an NSDictionary always the same like how they were specified when initializing the NSDictionary? Or should I better maintain a seperate NSArray if I really need to know the order of keys?
Upvotes: 13
Views: 16175
Reputation: 413
In fact, you can't even rely on the order being the same when running the program in two different devices, even if it's the exact same program and the exact same version of the operating system.
For example, if you run the program on an iPad Air, the ordering of the elements inside NSDictionary may be different than when running the same program on an iPad Retina, even if the iOS version is exactly the same.
In short, the ordering of elements in NSDictionary must never be relied on. You must always assume they may be in any unspecified order, which may be different on different devices.
Upvotes: 1
Reputation: 2795
Matt Gallagher wrote a blog post titled “OrderedDictionary: Subclassing a Cocoa class cluster” covering exactly this issue, complete with sample code.
Upvotes: 3
Reputation: 15013
NSDictionary keys & values are not ordered. Your options:
Upvotes: 3
Reputation: 46985
keys are never guaranteed to be in the same order when accessing an NSDictionary. If the keys can be compared (which I assume they can be given your question), then you can always sort them if you need to access them in sorted order.
You would need to do this by reading the keys into an array first and sorting the array of course.
Upvotes: 1
Reputation: 8813
NSDictionary, according to Apple's reference, is basically a wrapper around a hash table. So no, they are not guaranteed to be in any particular order.
Upvotes: 1
Reputation: 400642
No, they are not ordered. As long as you don't add or remove any elements from the dictionary, they will remain in the same order, but as soon as you add or remove an element, the new order will be completely different.
If you need the keys/values to be ordered, use an NSArray (or some other ordered data structure) instead.
Upvotes: 19