Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary allKeys - does it always return the same order?

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,

like image 246
KerrM Avatar asked Mar 05 '12 22:03

KerrM


People also ask

Is NSDictionary ordered?

NSDictionary keys & values are not ordered.

What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both.

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.

What is a NSDictionary object?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

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.

like image 152
Lily Ballard Avatar answered Oct 04 '22 22:10

Lily Ballard


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/

like image 42
peterept Avatar answered Oct 04 '22 22:10

peterept