NSDictionary allKeys - does it always return the same order?

时光怂恿深爱的人放手 提交于 2019-12-08 16:55:21

问题


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,


回答1:


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.




回答2:


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/




回答3:


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.



来源:https://stackoverflow.com/questions/9575387/nsdictionary-allkeys-does-it-always-return-the-same-order

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