“哈希”是什么意思? Objective-C 中的方法
有时,当我查看对象响应的选择器列表时,我会看到 hash
出现。有一段时间,我一直想知道这意味着什么,但我一直没有弄清楚。
如果您能告诉我选择器的作用以及这样做的常见用途,我将非常感激。
Occasionally, when I am looking down the list of selectors that a object responds to, I see hash
come up. For a while now, I have wondered what it meant, but I never came around to finding out.
I would really appreciate it if you could tell me what the selector does and common uses for doing so.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它计算对象的哈希值,这在哈希表中特别有用,例如当对象用作 NSDictionary 的键时。
对象
哈希
必须具有以下属性:NSDictionary
查找的性能就越好。有关更多信息,阅读 NSObject 协议文档,其中定义了此
hash
方法。例如,字符串的
哈希
函数可以是该字符串的字符数,或其字符的ascii代码之和,或任何类似的值。当您搜索时对于 NSDictionary 中的给定键,一种解决方案是将搜索到的键与字典中的所有其他键进行比较,这需要循环遍历所有键并调用 isEqual > 在每个键上,这将需要如果字典有很多条目,时间会很长。因此,Cocoa 将计算搜索到的键的哈希值,并将其与字典中键的所有(预先计算的)哈希值进行比较。
这更加高效,因为它只需要在
NSUInteger
值之间进行比较,即使NSDictionary
的键是NSString
或其他对象,所以这确实更快。一旦找到与搜索到的键的哈希值具有相同哈希值的键,它就可以循环遍历具有该哈希值的所有键,并通过调用 isEqual 将它们与搜索到的键进行比较,但在此阶段将有更少的密钥进行循环(如果密钥的散列确实是唯一的,甚至可能只有一个)
It computes a hash of the object, which is especially useful in HashTables like when the object is used as a key for an
NSDictionary
.An object
hash
has to have the following properties:NSDictionary
lookup will be.For more info, read the NSObject Protocol documentation where this
hash
method is defined.For example the
hash
function for a string could be the number of characters of this string, or the sum of the ascii codes of its character, or anything similar.When you search for a given key in an
NSDictionary
, one solution would be to compare the searched key with all other keys in the dictionary, which would need to loop thru all the keys and callisEqual
on each key, and that will take a long time if the dictionary have a lot of entries. So instead, Cocoa will compute the hash of the searched key, and compare it with all the (pre-computed) hashes of the keys in the dictionary.This is much more efficient because it will only need to make comparisons between
NSUInteger
values, even if the keys of theNSDictionary
areNSString
s or other objects, so this is really faster.Once it has found the keys that have the same hash as the hash of the searched key, it can then loop thru all the keys with this hash and compare them with the searched key by calling
isEqual
, but at this stage there will be much less keys to loop thru (and even possibly only one if the hash of the key is really unique)它用于在关联数组数据类型(例如
NSDictionary
。It's used for implementing efficient hash tables in associative array data types such as
NSDictionary
.