Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suitable key for 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.

like image 512
Nathan Day Avatar asked Apr 18 '12 00:04

Nathan Day


3 Answers

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.

like image 155
xzgyb Avatar answered Oct 20 '22 02:10

xzgyb


How an object behaves as a key depends on how it implements isEqual:. This will determine whether two keys collide.

For example, index paths are equal - and therefore will collide - when the paths have the same set of indexes. So two distinct objects describing the same path will be seen by the dictionary as the same key... probably how you'd like it to be.

like image 31
danh Avatar answered Oct 20 '22 04:10

danh


There are three requirements for NSDictionary keys:

  1. Support the NSCopying protocol
  2. Reasonable -hash method
  3. isEqual

NSIndexPath should be fine.

like image 2
EricS Avatar answered Oct 20 '22 03:10

EricS