boyfarrell.com

27 May 2007

Using NSDictionary to store custom classes

If you want to integrate your code with Cocoa, you will sooner or later find yourself wanting to store your objects; or use them as keys, in a NSDictionary. Before they can be use in this way you must first implement two methods that cocoa collection classes expect;

-(unsigned) hash; and

-(BOOL)isEqual:.

Hashing is a method of increasing the efficiency of lookups for data in collections; this method is used by NSDictionary. The check for equality is also required as it is closely related to the value of the hash. Cocoa assumes that if two objects have the same hash then they must be equal.

In searching the net CocoaDev has a nice page on implementing hash and isEqual which will also point you in the direction of Apple’s original documentaion on the matter.

The basic premise of the above articles is to add 3 methods to your class; hash and isEqual which are overridden inherited methods and isEqualToYourClass:, which it your custom method specific to the class which will be called by the previous method. NB – obviously replace ‘…YourClass:’ with the name of your your class when naming this method!

No Comments currently posted.

Post a comment on this entry: