关于 isEqual 和 hash

About isEqual and hash

这个问题是关于objc中的选择器isEqual

我知道什么时候对象使用isEqual,他们比较hash,但是如何理解下面的代码:

NSString *string = [NSString stringWithFormat:@"%d", 1];
NSLog(@"%d", [@"1" hash] == [string hash]); // output 1

我读取对象的哈希值不能相同,为什么输出是1?

I know when object use isEqual, they compared hash

这是不正确的。 isEqual 比较对象而不使用 hash(通常)。

I read the hash of object can not be same

同样不正确,哈希 必须 对相等的对象相等,可以 对不相等的对象相同。由于 hash 是一个 int,因此只有 2^32 个可能的值,不足以使其对每个可能的对象都是唯一的(除非该对象本身等于或小于 32 位)。

关于 hash 的唯一规则是:如果 [a isEqual:b] 为真,则此 必须 也为真:[a hash] == [b hash].

因此,由于您的两个字符串相等,都 "1",因此哈希值也应该相等。