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: Seth Willits <email@hidden>
- Date: Thu, 20 Aug 2009 20:51:14 -0700
On Aug 20, 2009, at 2:31 PM, Alastair Houghton wrote:
The -hash method is important for objects that are used as keys in
associative collections. So the worry about the hash value changing
when an object's properties are altered is a bit of a red herring,
because you *aren't supposed to change keys in associative
collections*. If you do that in just about *any* implementation,
ObjC or otherwise, you'll get undefined behaviour.
So, in practice, it's perfectly safe in 99.9% of cases to base your
hash off your object's properties. In the specific case when you're
mutating objects that are keys in associative collections
(NSDictionary and NSSet being the primary examples, along with their
CoreFoundation counterparts), if you change a property that affects
*either* -isEqualTo: *or* -hash, you need to remove the object
before mutating it and then add it back again afterwards.
The documentation, nor did many others' comments on this topic, make
it clear that the mutability is only a problem for the *keys*. Others
and the docs talk about (paraphrasing) "putting an object into a
collection", not "using an object as a key in an associative
collection."
Here are the docs:
"If a mutable object is added to a collection that uses hash values to
determine the object’s position in the collection, the value returned
by the hash method of the object must not change while the object is
in the collection."
If I follow this sentence, it says that if I put a (mutable string)
into a (dictionary), the value returned by the -hash method of (the
string) must not change while it's in the collection. It does *not*
say that the hash method of the *KEY* can't change, it says the hash
value of the object stored in the collection. Now maybe this is worded
really poorly, but I think this is where the confusion comes from. It
seems to be in direct contradiction to what you're saying.
If it were only an issue for keys, then this is, like you said, no big
deal. If my reading of the documentation is correct, then it's a much
more prevalent problem, as others seem to be saying.
--
Seth Willits
_______________________________________________
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