Are keys and values in an NSDictionary ordered?

筅森魡賤 提交于 2019-12-17 06:45:31

问题


I mean: Is the order of keys and values in an NSDictionary always the same like how they were specified when initializing the NSDictionary? Or should I better maintain a seperate NSArray if I really need to know the order of keys?


回答1:


No, they are not ordered. As long as you don't add or remove any elements from the dictionary, they will remain in the same order, but as soon as you add or remove an element, the new order will be completely different.

If you need the keys/values to be ordered, use an NSArray (or some other ordered data structure) instead.




回答2:


NSDictionary keys & values are not ordered. Your options:

  • Maintain a separate array of the keys in the order you desire
  • Write or find an existing class that is a wrapper for the above
  • Write or find an existing subclass of NSDictionary that adds APIs for ordering



回答3:


Matt Gallagher wrote a blog post titled “OrderedDictionary: Subclassing a Cocoa class cluster” covering exactly this issue, complete with sample code.




回答4:


NSDictionary, according to Apple's reference, is basically a wrapper around a hash table. So no, they are not guaranteed to be in any particular order.




回答5:


keys are never guaranteed to be in the same order when accessing an NSDictionary. If the keys can be compared (which I assume they can be given your question), then you can always sort them if you need to access them in sorted order.

You would need to do this by reading the keys into an array first and sorting the array of course.




回答6:


In fact, you can't even rely on the order being the same when running the program in two different devices, even if it's the exact same program and the exact same version of the operating system.

For example, if you run the program on an iPad Air, the ordering of the elements inside NSDictionary may be different than when running the same program on an iPad Retina, even if the iOS version is exactly the same.

In short, the ordering of elements in NSDictionary must never be relied on. You must always assume they may be in any unspecified order, which may be different on different devices.



来源:https://stackoverflow.com/questions/1295459/are-keys-and-values-in-an-nsdictionary-ordered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!