views:

244

answers:

4

I've run into the same problem as found in this question. However, I have a follow-up question. I seem to be in the same situation as the original asker: I have a plist with a hierarchy of dictionaries that define a configuration screen. These are not mutable and will stay the same throughout the application. Since the original discussion seems to focus on problems arising from mutating the dictionary, I must ask for comfirmation: is the order of a dictionary guaranteed the same as they are in the plist, i.e. as it is read (with initWithContentsOfFile)? Can I use allKeys on it in this case to get a correct-order array of keys if the dictionary never changes?

+4  A: 

No, the keys are not likely to appear in the same order as your plist file. I can't look under the hood, but I would guess that the keys are ordered in whatever way that provides an efficient look-up. The documentation for allKeys says that the order of the elements in the array is not defined.

dreamlax
My app does show them in the same order as the plist, which was one of the reasons I started wondering. But I now know that it's undefined nonetheles.
Thaurin
+4  A: 

If you need an NSDictionary that maintains order, take a look at CHDataStructure's CHOrderedDictionary, which does exactly that. I use it all the time.

Dave DeLong
I need it on the iPhone, so Cocoa Touch. I wonder if it runs on that? In any case, I'll answer my own question: no, NSDictionary can apparently never be expected to be in any order. So, I'm doing what I've seen others suggest: include an array with the order and key "_order". People have been saying this clunky double data-keeping isn't that clunky at all in their opinion. Still clunky, though.
Thaurin
Yes, the CHDataStructures runs on both Mac and iPhone.
Dave DeLong
+1  A: 

I would not assume that the keys will be in any kind of order because allKeys does not guarantee order.

Internally, NSDictionary uses a hash table.

From allKeys description:

The order of the elements in the array is not defined.

If you want to display values in some order then get the keys, sort the keys array and then get the value for each key.

stefanB
+1  A: 

Nothing at all is guaranteed about order. It’s not even guaranteed that iterating over a dictionary twice will give you the keys in the same order.

Ahruman