问题描述
有一种方法可以确定类是否适合作为键,并且将按照您的期望工作,例如,我想在 NSDictionary 中使用 NSIndexPath 但我不知道如果两个不同的 NSIndexPath 实例具有相同的整数值将总是返回相同的哈希值。
Apple的NSObject的isEqual文档说:
查看以下代码:
NSIndexPath * indexPath1 = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath * indexPath2 = [NSIndexPath indexPathForRow:0 inSection:0];
NSObject * obj1 = [[NSObject alloc] init];
NSObject * obj2 = [[NSObject alloc] init];
NSLog(@NSIndexPath isEqual的结果:%d,[indexPath1 isEqual:indexPath2]);
NSLog(@NSObject isEqual的结果:%d,[obj1 isEqual:obj2]);
输出结果:
NSObject isEqual 的实现是两个对象的地址
和哈希实现是返回对象的地址。
NSIndexPath 继承自 NSObject ,根据NSIndexPath isEqual输出结果,
NSIndexPath的isEqual实现应重写超类的isEqual方法,NSIndexPath也重写超类的hash方法。 / p>
在这里,NSIndexPath也符合NSCopying协议。
所以NSIndexPath可以用作Key类NSDictionary。
Is there a way to determine if a class is suitable as a key and will work as you expect, for example I want to use NSIndexPath as a key in NSDictionary but I don't know for certain if two different NSIndexPath instances with the same integer values will always return the same hash value.
Apple's NSObject's isEqual document says:
Look the following code:
NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:0 inSection:0];
NSObject *obj1 = [[NSObject alloc] init];
NSObject *obj2 = [[NSObject alloc] init];
NSLog(@"NSIndexPath isEqual's Result: %d", [indexPath1 isEqual:indexPath2]);
NSLog(@"NSObject isEqual's Result: %d", [obj1 isEqual:obj2]);
Output Result:
The implementation of NSObject isEqual is that comare the address of two objects, and hash implementation is that return object's address.
NSIndexPath is inherited from NSObject, according to NSIndexPath isEqual output result, NSIndexPath's isEqual implementation should override superclass's isEqual method, and NSIndexPath also override superclass's hash method.
In attition, NSIndexPath also conform to the NSCopying protocol.
So NSIndexPath can be used as the Key class of NSDictionary.
这篇关于适用于NSDictionary的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!