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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to