Re: NSDictionary objectForKey and non-standard key classes
Re: NSDictionary objectForKey and non-standard key classes
- Subject: Re: NSDictionary objectForKey and non-standard key classes
- From: "Erik M. Buck" <email@hidden>
- Date: Tue, 28 Aug 2001 15:46:55 -0500
For use as dictionary keys, two objects that return YES from isEqual: must
also return the SAME hash value for -hash. The default implementation
of -hash inherited from NSObject uses the address of the object as the basis
for the hash key. As a result, if you call -objectForKey: using an object
at a different address from the object used to -setObject:forKey: then you
will not get the expected object.
The solution is to follow the documentation and make sure that -hash returns
the same value for two objects that return YES from -isEqual:
See the first result from the following search:
http://www.google.com/search?num=100&hl=en&safe=off&q=NSDictionary+hash+deve
loper+apple
<QUOTE>
hash
- (unsigned)hash
Returns an integer that can be used as a table address in a hash table
structure. If two objects are equal (as determined by the isEqual: method),
they must have the same hash value. This last point is particularly
important if you define hash in a subclass and intend to put instances of
that subclass into a collection.
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. To accomplish this, either the hash method must not rely on any
of the object's internal state information or you must make sure the
object's internal state information does not change while the object is in
the collection. (Note that it can be difficult to know whether or not a
given object is in a collection.)
<END QUOTE>
See also:
http://www.osxfaq.com/Documentation/Final/Developer/Cocoa/TasksAndConcepts/P
rogrammingTopics/Collections/Concepts/Dictionaries.html