Reputation: 5240
I'm fairly new to Objective-C and I was working with NSDictionaries today and came across the allKeys method. As I understand, it returns an NSArray containing the keys for the dictionary in a random order. However, is this order always the same? ie, if I call allKeys on the same dictionary 20 times in a row am I guaranteed to get the same order of results?
Thanks,
Upvotes: 9
Views: 5636
Reputation: 4427
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/
Upvotes: 1
Reputation: 185841
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.
Upvotes: 8
Reputation: 21383
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.
Upvotes: 0