Re: Implementing isEqual: and hash
Re: Implementing isEqual: and hash
- Subject: Re: Implementing isEqual: and hash
- From: Graham Cox <email@hidden>
- Date: Sat, 23 Aug 2008 23:39:21 +1000
On 23 Aug 2008, at 9:52 pm, Jean-Daniel Dupas wrote:
Le 23 août 08 à 13:41, Graham Cox a écrit :
I have a class for which equality can be defined as having the same
internal string value (which happens to be a UUID-turned-string). I
can easily implement isEqual: based on that but the docs say I also
need to implement -hash. Any pointers on what is a good way to do
that? Could I just safely defer to the -hash returned by the string
in question?
Yes, that the way to do it.
To understand what an hash is and how it is used, I suggest you read
the hash table article in wikipedia.
http://en.wikipedia.org/wiki/Hash_table
Hash tables are used in Cocoa in NSDictionary, NSSet, NSHashTable,
NSHashMap and maybe more. When you understand how it works, choosing
the implementation should be obvious.
Thanks for that. I'm pretty familiar with hash tables in general (and
in quite a bit of theory too) but I wasn't able to find out what Cocoa
uses for its hashing function or how "good" this needed to be to work
well with the built-in classes. However, by deferring to the string I
can avoid the issue altogether.
For curiosity's sake, I would be interested to know what sort of
hashing functions Cocoa does use. I haven't come across the need to
generate one for any of my custom classes before so it's not something
I need right now, but every bit of knowledge is worth having.
For example, here's a very crude hash function I used in a very simple
symbol table implementation from a long while ago. I imagine most hash
functions in Cocoa would be more sophisticated.
unsigned long ZHashTable::Hash( const char* name )
{
register unsigned long h = 1;
register char* p = (char*) name;
register char c;
while(( c = *p++ ) != 0 )
h *= (unsigned long) c;
return h % kHashTableSize;
}
cheers, Graham_______________________________________________
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