要成为 NSDictionary 的键,class 还必须实现 isEqual: 和哈希吗?
To be a key of an NSDictionary, must a class also implement isEqual: and hash?
我知道 class 必须实现 NSCopying
才能成为 NSDictionary
的键,但我也在实现 isEqual:
和 hash
有必要还是建议?
如果是,为什么?
是的。
为什么?
考虑访问字典的元素,NSDictionary
如何找到与键关联的对象?通过比较您提供的键值与字典中的键。
当你实现isEqual:
时,你也实现了hash
,这是一个规则,比较相等的对象必须具有相同的散列。进一步考虑字典如何组织key/value对的存储,它使用基于散列的存储结构。
HTH
附录
看到我猜的是 你也问过我将符合上述条件 "Yes":
如果 class 继承了 isEqual:
和 hash
方法,这些方法适当地为自己定义了相等性,则它不需要用自己的版本覆盖这些方法。如果 class 直接继承自 NSObject
.
,这很可能 not 为真
A key-value pair within a dictionary is called an entry. Each entry
consists of one object that represents the key and a second object
that is that key’s value. Within a dictionary, the keys are unique.
That is, no two keys in a single dictionary are equal (as determined
by isEqual:). In general, a key can be any object (provided that it
conforms to the NSCopying protocol—see below), but note that when
using key-value coding the key must be a string (see Key-Value Coding
Fundamentals). Neither a key nor a value can be nil; if you need to
represent a null value in a dictionary, you should use NSNull
我知道 class 必须实现 NSCopying
才能成为 NSDictionary
的键,但我也在实现 isEqual:
和 hash
有必要还是建议?
如果是,为什么?
是的。
为什么?
考虑访问字典的元素,NSDictionary
如何找到与键关联的对象?通过比较您提供的键值与字典中的键。
当你实现isEqual:
时,你也实现了hash
,这是一个规则,比较相等的对象必须具有相同的散列。进一步考虑字典如何组织key/value对的存储,它使用基于散列的存储结构。
HTH
附录
看到我猜的是
如果 class 继承了 isEqual:
和 hash
方法,这些方法适当地为自己定义了相等性,则它不需要用自己的版本覆盖这些方法。如果 class 直接继承自 NSObject
.
A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see Key-Value Coding Fundamentals). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull