views:

104

answers:

1

I've read that -hash does not return the same value on different architectures. However, I don't currently see this in the docs.

Is there a better way to store NSView's in a dictionary without subclassing?

A: 

You might be confused as to what hash means in this context. Hash is just a number which Cocoa collection classes use internally to improve performance. NSObject implements this method, so you don't have to ever override it unless a better, more meaningful hash algorithm results in better performance while comparing/searching objects in an array or a dictionary.

Since no objects should cache their hash values on disk, the comment just implies you should not rely on the concrete hash values returned by Apple's classes. It is considered a minor implementation detail.

NSDictionary retains its values but copies the keys. So you don't have to do anything to keep your views in a dictionary as values, but if you want to use the views as keys, you have to implement -copyWithZone: method.

Read more in Apple's documentation.

Costique
Yes, I didn't specify in the original question, but I DO want to use the views as keys. Basically, I'm trying to keep a bunch of metadata about several different kinds of views and I need to be able to look up the metadata given the object. Are you saying I MUST subclass and override the copyWithZone: method in order to do this? Is there no other way?
Daniel Weber
@Daniel Weber: If you want to use NSDictionary, yes, you have to accept NSDictionary's behavior. I think a better question, though, is why you're trying to keep metadata about the views. Normally in such a case, views would be representing model objects, and it would make more sense to store the metadata in the model layer.
Chuck
Yes, when you put it like that it doesn't seem to make sense. However, I'm working on an Interface Builder type of program and I'm using lots of different standard controls (buttons, textfields, etc.). When one is clicked in my program, I need to be able to access some custom properties about that control. I was trying to avoid subclassing everything because all I really need is a couple extra string and int properties, I'm not redefining any behavior. Is subclassing really the best way?
Daniel Weber
You can use CFDictionary with custom callbacks which retain keys rather than copy them. However, note that the reason why NSDictionary copies keys is to prevent them from changing behind NSDictionary's back. Key mutation may (and generally should) affect their hash values, which breaks the internal mechanism too easily.
Costique
As an alternative where mutation won't be a problem, assuming the views aren't going to disappear without warning, you could store the pointer value in an NSValue and use that for the key. Alternatively, you could use the runtime's associated objects support: http://developer.apple.com/mac/library/documentation/cocoa/reference/objcruntimeref/Reference/reference.html
Chuck