NSDictionary 中的键和值是有序的吗?
我的意思是: NSDictionary 中键和值的顺序是否始终与初始化 NSDictionary 时指定的顺序相同?或者如果我真的需要知道键的顺序,我应该更好地维护一个单独的 NSArray 吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,他们没有被订购。只要您不从字典中添加或删除任何元素,它们就会保持相同的顺序,但一旦您添加或删除元素,新的顺序就会完全不同。
如果您需要对键/值进行排序,请使用 NSArray (或其他一些有序数据结构)。
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.
NSDictionary 键和值未排序。您的选择:
NSDictionary keys & values are not ordered. Your options:
Matt Gallagher 写了一篇博客文章,标题为 “OrderedDictionary:子类化 Cocoa 类簇” 完全涵盖了这个问题,并附有示例代码。
Matt Gallagher wrote a blog post titled “OrderedDictionary: Subclassing a Cocoa class cluster” covering exactly this issue, complete with sample code.
NSDictionary,根据 Apple 的参考 ,基本上是哈希表的包装。所以不,不能保证它们按任何特定顺序排列。
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.
访问 NSDictionary 时,永远不能保证键的顺序相同。如果可以比较键(我假设它们可以给出您的问题),那么如果您需要按排序顺序访问它们,您可以随时对它们进行排序。
您需要首先将键读入数组并当然对数组进行排序来完成此操作。
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.
事实上,在两个不同的设备上运行程序时,您甚至不能依赖相同的顺序,即使它是完全相同的程序和完全相同的操作系统版本。
例如,如果您在 iPad Air 上运行该程序,则 NSDictionary 内元素的顺序可能与在 iPad Retina 上运行相同程序时不同,即使 iOS 版本完全相同。
简而言之,决不能依赖 NSDictionary 中元素的顺序。您必须始终假设它们可能采用任何未指定的顺序,并且在不同设备上可能有所不同。
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.