tags:

views:

639

answers:

3

How do I compare two objects of a custom class? My idea was to add an additional method to the class in which I can compare the current object with another object of the same kind.

So I can write my own code how each field of the class is compared.

This is how I would do it. Or are there some predefined methods to do that? Like "isEqualTo" of the NSString class?

+3  A: 

The standard way is to override - (BOOL)isEqual:(id)anObject and - (NSUInteger)hash.

You should read the documentation for NSObject protocol and this SO question has some interesting answers on how to write your hash method.

pgb
A: 

Look at the isEqual: and the compare: method.

Georg
+3  A: 

The pointers to -isEqual: are good, but if you implement -isEqual:, you absolutely must also implement -hash in such a way that if two objects return YES for -isEqual: they will also return the same value for -hash. Implementing isEqual: without also implementing -hash leads to some very surprising bugs when you use Collections like NSArray.

For new developers, I tend to recommend against overloading -isEqual:. I recommend instead using the same technique as NSString, and create a custom -isEqualToFoo: (where Foo is your class) until you understand the impact of -isEqual: on collections and specifically want this behavior. Overloading -isEqual: powerful, but the bugs you can create are subtle. Creating your own custom comparator is safer and clearer in many cases.

Rob Napier
Hi Rob. Great answer! Since I am a "new developer" I will do exactly as you suggested. This is what I had in mind in the first place. Many thanks.
Holli
Thanks for pointing this out. While I still don't understand WHY isEqual isn't enough to determine equality, I was getting some REALLY strange NSCountedSet behavior because I had no idea that hash came into play with generic equality testing.
LucasTizma