user445929
user445929

Reputation:

What's wrong with using NSObject's hash to create an NSMutableDictionary key?

In a few places I've needed object-to-object mappings, and have used NSMutableDictionary as a lookup table. The key has been a boxed NSObject hash, eg:

  [dict setObject:newObject forKey:[NSNumber numberWithUnsignedInt:[keyObject hash]]];

where keyObject is an instance of a custom class, which inherits NSObject's - (NSUInteger)hash implementation as-is. I have retained references to keyObject elsewhere, which I can use to get hold of newObject thusly:

[dict objectForKey:[NSNumber numberWithUnsignedInt:[keyObject hash]]]

This has seemed to work so far, though the app concerned is yet young.

Matt Gallagher, however, writes about this approach:

(don't laugh, I've seen it done)

which slightly undermines my confidence (and as this is for an iOS app I can't use his suggested NSMapTable).

Can anyone point out what's wrong with using NSObject's hash in this way, and what might be a better approach for a simple object-object mapping for an iOS app?

Upvotes: 3

Views: 3469

Answers (2)

al45tair
al45tair

Reputation: 4433

In addition to the non-uniqueness of hashes, if you shoehorn them into an unsigned int as you have done here, you’ve actually guaranteed that even a -hash method that returns the object pointer directly will not necessarily result in a unique key.

If you are going to do this, then rather than using NSNumber, at least use NSValue with the +valueWithPointer: and -pointerValue methods.

If you really want an NSDictionary interface and can’t use NSMapTable for some reason, you could use Core Foundation instead to create a dictionary that has raw object pointers as its keys. If you do that, you can even choose how the memory management works for objects you’re using as keys in the dictionary; for instance, you may want to retain the keys, you may want to copy the keys, or you may decide that all you care about is the pointer value itself.

Upvotes: 2

Jon Reid
Jon Reid

Reputation: 20980

Hashes are not guaranteed to be unique.

Upvotes: 2

Related Questions