I was working on a utility class and was playing with the idea of using the id of an object (e.g. NSObject) as a key in NSDictionary. Setting it directly doesn’t work though:

The above will lead to an exception like this:

NSInvalidArgumentException, reason: '-[NSObject copyWithZone:]: unrecognized selector
sent to instance 0x7ca6160'


The solution I arrived at was to use the string representation of the object. Simply casting the object to NSString will not work though:

Using a new NSString instance will work however:

Update

curthard89 from Forrst pointed out that it would be better to use [NSObject hash] instead of typecasting to string. The reason is NSDictionary and NSArray string representations can get really long and would be inefficient. I’m now using this technique: