Overriding isEqual:
Ideally, I would always read all available documentation before I start programming something... However, I don't. That's why it took me a while to figure out that it is not enough to implement isEqual:
in a new class I was working on to ensure that equality for that class is handled correctly (in Objective-C).
This is only enough when you do comparisons between objects manually by calling isEqual:
. On other occasions (e.g. when you call addObject:
on an NSMutableSet
), equality is computed by some magic combination of isEqual
and the object's hash value, returned by hash
. If you want to make sure two objects really are considered the same, make sure that both isEqual:
and hash
return the same value! When equality is supposed to be based on the value of some NSString member of your class (as it was the case for me), this is very easy to achieve - just let hash
return the hash of that string. E.g., in my case equality depends on the value of the url
member, which is a string. The code then looks like this:
- (unsigned)hash { return [url hash]; }
I got the solution off this thread on Cocoabuilder.