NSDictionary allKeys - does it always return the same order? NSDictionary allKeys - does it always return the same order? xcode xcode

NSDictionary allKeys - does it always return the same order?


If you call the method 20 times in a row on a dictionary that is not being mutated, it most likely will return the same order. That said, I would strongly discourage you from relying on this, as it's highly dependent upon implementation details. The only reason I'm saying that it will most likely return the same order is because accessing a dictionary should not mutate any internal structures, and in the absence of mutation, the only other way to get a different order would be to explicitly introduce nondeterminism, i.e. relying on global state, such as a random number generator or the CPU's clock, and I find it extremely doubtful that NSDictionary does any of this.

If you need to ensure the same ordering of keys, you should probably just sort them once you fetch them from the dictionary.


NSDictionary objects are unordered to maintain performance.

If you need an ordered dictionary, look at this project:

http://code.google.com/p/cocoa-sorted-dictionary/


The way to figure this out is to write a quick test program. Really, you should never rely on non-guaranteed, non-documented results like this. It's bad programming practice, and is fairly likely to break with a new OS release.

If you need the keys that come back to be in a particular order, you should sort them after retrieving them. You can do that with the -[NSArray sortedArrayUsing...] group of methods.