Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do implement a custom key for NSDictionary

I'm trying to implement a class for use as a key in an NSDictionary. The docs say that in order to be used as a key the object needs to implement the NSCopying protocol, which I've done.

I'm seeing some very strange behaviour, where values seem to mysteriously become nil even though I can see the objects being stored correctly in the dictionary.

I've implemented copyWithZone: and isEqual: correctly as far as I can see but it's still not working.

like image 722
Darren Avatar asked Nov 22 '25 19:11

Darren


1 Answers

What the documentation does not make clear is that to use an object as the key in a NSDictionary it must override BOTH the isEqual: and hash methods, as well as implementing NSCopying.

The contract for isEqual: and hash is that if isEqual: returns YES for 2 objects then their hash methods MUST return the same value. It's okay for 2 objects that are NOT equal to have the same hash but if they ARE equal then they MUST have the same hash.

Failing to correctly override hash will lead to all sorts of hard to debug issues when you try reading and writing from the dictionary.

like image 177
Darren Avatar answered Nov 24 '25 11:11

Darren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!