Nathan Day
Nathan Day

Reputation: 6037

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.

Upvotes: 13

Views: 3312

Answers (3)

xzgyb
xzgyb

Reputation: 452

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.

Upvotes: 9

EricS
EricS

Reputation: 9768

There are three requirements for NSDictionary keys:

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

NSIndexPath should be fine.

Upvotes: 2

danh
danh

Reputation: 62686

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.

Upvotes: 4

Related Questions