Are keys and values in an NSDictionary ordered?
Solution 1:
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.
Solution 2:
NSDictionary keys & values are not ordered. Your options:
- Maintain a separate array of the keys in the order you desire
- Write or find an existing class that is a wrapper for the above
- Write or find an existing subclass of NSDictionary that adds APIs for ordering
Solution 3:
Matt Gallagher wrote a blog post titled “OrderedDictionary: Subclassing a Cocoa class cluster” covering exactly this issue, complete with sample code.
Solution 4:
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.