Re: When do I need to override hash?
Re: When do I need to override hash?
- Subject: Re: When do I need to override hash?
- From: Clark Cox <email@hidden>
- Date: Thu, 20 Aug 2009 21:36:27 -0700
On Thu, Aug 20, 2009 at 9:09 PM, Jeff Laing<email@hidden> wrote:
>> Core Data doesn't use random objects as keys in dictionaries or sets
>> for this reason. It's not that we don't trust you, but ... to
>> prevent misunderstandings, all NSManagedObject subclasses are
>> forbidden from overriding -hash and -isEqual.
>
> I have to admit, I didn't know this bit but I see it in the developer library along with a bunch of others.
>
>> If you need to know whether or not another object has put your object
>> into an NSDictionary, you're probably doing something wrong. Do you
>> have a specific concern about Core Data using your objects ?
>
> No, I guess the point I was trying to make was that this discussion seemed to have touched on "if you put your objects into an NSSet then you'll need to be more careful about the implementation of -hash, etc". I was trying to point out that just because my application code doesn't go anywhere near NSSet, its conceivable (to me) that Core Data (for example) might be storing dirty objects in an NSSet "behind your back". So you can't "not implement -hash, etc properly" and hope everything will work.
The solution is simple:
If you implement -hash, you must implement -isEqual:
If you implement -isEqual:, you must implement -hash
If -isEqual: returns true for two given objects, those objects must
return the same value for -hash
If you don't implement either, NSObject's implementations are fine
also. i.e. NSObjects implementations are basically:
-(NSUInteger)hash { return (NSUInteger) self; }
-(BOOL)isEqual:(id)obj { return self == obj; }
--
Clark S. Cox III
email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden