views:

70

answers:

1

I'm trying to make a dictionary store a map of delegates that correspond to a protocol. I need some consistent key that represent a protocol.

For example the following gives me a protocol object

Protocol * one = @protocol(SomeProtocolDefinedEarlier);

And it responds to [one hash] but the hash isn't the same each time you get a protocol object for the same protocol. Is there some name message or something I can use to identify it?

+4  A: 

Well, protocols must have unique names (otherwise they'd conflict with each other), so how about:

Protocol * aProtocol = ...
NSString * protocolIdentifier = NSStringFromProtocol(aProtocol);
Dave DeLong
Exactly what I was looking for. How does one find that sort of thing in the docs?
Sean Clark Hess
While I have you here, what is the best way to get a key for some random object (instance?) I can ask for [obj hash] and turn it into string, but I think I read that was a bad idea. Is there something equally cool for objects?
Sean Clark Hess
@Sean - They're in the Foundation Functions Reference: http://developer.apple.com/mac/library/documentation/cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html As for uniquely identifying an instance, you can either use the hash or the address of the object.
Dave DeLong
@Sean - The Objective-C spec states that each object instance is uniquely identified by its reference (type `id`). In the current implementation, `id` is a pointer to a struct and hence the memory address is the the instance ID. You could use an `NSDictionary` or `NSHashMap` keyed by instance directly.
Barry Wark
@Barry, I swear I tried that and it didn't work. Thanks, I'll try it again
Sean Clark Hess
@Barry - doesn't work unless the objects conform to NSCopying, which copies them instead of using the hash. Not what I wanted at all. NSHashMap isn't available on iphone. I solved it by creating a category for dictionary that adds some "weak keys" functions.
Sean Clark Hess