有没有一种方法可以确定某个类是否适合作为键并且可以按您期望的方式工作,例如,我想使用 NSIndexPath 作为 NSDictionary 中的键,但是我不确定是否两个不同的 NSIndexPath具有相同整数值的实例将始终返回相同的哈希值。

最佳答案

苹果公司的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's Result: %d", [indexPath1 isEqual:indexPath2]);
NSLog(@"NSObject isEqual's Result: %d", [obj1 isEqual:obj2]);
输出结果:

NSObject的实现是等于是两个对象的地址比较,
哈希实现是返回对象的地址。
NSIndexPath 根据NSIndexPath isEqual输出结果从 NSObject 继承而来,
NSIndexPath的isEqual实现应覆盖父类(super class)的isEqual方法,而NSIndexPath也应覆盖父类(super class)的hash方法。
在态度上,NSIndexPath也符合NSCopying协议(protocol)。
因此,NSIndexPath可用作NSDictionary的Key类。

关于objective-c - 适用于NSDictionary的 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10201233/

10-12 05:42