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,
NSDictionary keys & values are not ordered.
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.
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.
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With