views:

1038

answers:

4

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?

+3  A: 

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.

Adam Rosenfield
+1  A: 

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.

ennuikiller
+1  A: 

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.

Josh Lindsey
How do they access that hash table? Have never seen a plain hash table, but would like to know how that looks like. Is that a big difference from using two synchronous NSArray internally?
HelloMoon
Are you asking what a hash table looks like as a data structure? Wiki has a pretty good explination: http://en.wikipedia.org/wiki/Hash_table If you want to know how Apple specifically implements and accesses them, I'm afraid the only things available to us are the header files ;)
Josh Lindsey
so when I get that right, a hash table is almost all about a hash function that will calculate the correct array-index for a given string-key + the array size. Sounds hard to implement, but good for performance. If that's true it would not matter much how many items are added to an dictionary.
HelloMoon
+1  A: 

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
Mike Abdullah