Objective-C – How to use custom objects as dictionary keys

(Translated from my Chinese blog post)

Using custom objects as dictionary keys is very simple in Java. But in Objective-C, you have to do many things to achieve the goal.

In my previous post, I already discussed one possible solution. I even read the source code of OPENSTEP to figure out why it is the case. But that solution is a bit complicated. You need to implement NSCopying, and override equal and hash. Today, I found another solution by using NSValue, which tremendously simplifies the code.

Example code:

References:

http://stackoverflow.com/questions/11532306/using-an-object-as-key-for-nsdictionary

http://nshipster.com/nsvalue/

No Comments

Post a Comment