views:

35

answers:

1

I've read in Apples docu that (as I expected) an NSDictionary is not constrained just to strings for keys. There's also a post here confirming that Sets can be used. I want to use protocol objects but it' not happening. I initWithObjectsAndKeys and pass @protocol(MyGreatProtocol) as a key. Compiles but I get a runtime error saying something like "object [the protocol object] doesn't implement somethingorother - trouble ahead" then another error message saying something like "You see, I said it would cause problems. I'm bailing out of this!"

Ok, the wording of the second might have been slightly different, but sorry not at the comp right now and wanted to try clarify this before I really am back at it. Hope at least somebody will get the gist of my problem.

Maybe it's the way I'm referencing the protocol? I've played around with alternatives without success. And @protocol(Blah) returns a pointer? So can't really fathom why it's not working.

+2  A: 

You can use the functions NSStringFromProtocol and NSProtocolFromString if you wish to store protocol names in a dictionary. NSStringFromProtocol will return a string object that you can use as a key, and NSProtocolFromString will go the other way.

Key objects in a dictionary must conform to the NSCopying protocol, because the keys must be logically immutable.

dreamlax
Fantastic, thank you! Am sure that does it for me, can't wait to try out. Kicking myself for not finding that myself. it's exactly the kind of thing I had in mind. Was busy though looking in NSObject or similar for some sort of ObjectAsString method. That's late night programming for you - shoulda learnt years ago not to try to "look for answers" in the middle of the night, but go to bed and come back to it fresh. Thanks again.
Rich
No. Keys need not be immutable. They must conform to NSCopying as you correctly say, but they need not be immutable as long as any mutation does not change the result of -hash or the result of -isEqual:
JeremyP
@JeremyP: That's what I mean by 'logically' immutable.
dreamlax