NSDictionary allKeys - 它总是返回相同的顺序吗? [英] NSDictionary allKeys - does it always return the same order?

查看:707
本文介绍了NSDictionary allKeys - 它总是返回相同的顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective-C很新,我今天与NSDictionaries合作,碰到了allKeys方法。如我所知,它返回一个NSArray包含字典的键的随机顺序。但是,这个顺序总是相同吗?即,如果我在同一个字典上连续调用allKeys 20次,我保证得到相同的结果顺序?

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?

谢谢,

推荐答案

如果在字典上未连续调用方法20次, 会返回相同的订单。也就是说,我强烈建议你不要依赖这个,因为它高度依赖于实现细节。唯一的原因,我说,它很可能返回相同的顺序是因为访问字典不应该突变任何内部结构,并且在没有突变,唯一的其他方式得到一个不同的顺序将明确地引入非确定性,即依赖于全局状态,例如随机数生成器或CPU的时钟,并且我发现非常怀疑 NSDictionary

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 allKeys - 它总是返回相同的顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆