适用于NSDictionary的键 [英] Suitable key for NSDictionary

查看:144
本文介绍了适用于NSDictionary的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

Apple的NSObject的isEqual文档说:


如果两个对象相等,它们必须具有相同的哈希值。这最后一点是特别重要的
如果你定义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]);

输出结果:


NSIndexPath isEqual的结果:1



NSObject isEqual的结果:0


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:

If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.

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:

NSIndexPath isEqual's Result: 1

NSObject isEqual's Result: 0

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的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆