Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object keys with NSMutableDictionary (Objective-C)

I want to store a bunch of key value pairs, with the key being my own object (ObjectA) that inherits from NSObject, and the value being an int.
I am trying to use an NSMutableDictionary. I understand that you can only store object types in the dictionary, so I have the following:

id value = [NSNumber numberWithInt:my_number];

[[self dictionary] setObject:value forKey:myObjectA];

Now that gives me an error, saying

-[ObjectA copyWithZone:]: unrecognized selector sent to instance

which is fine, I understand that object keys need to implement the NSCopying protocol. However I then read that you can do this by wrapping your objects using NSValue.

Can someone please explain how I would wrap my objects, and how I can then find the value by the key? Am I still able to use dictionary objectForKey:myObjectA or do I have to wrap myObjectA with an NSValue object while I'm searching as well? Or should I be implementing NSCopying on my custom class, or using a string key instead?

I am looking for this simplest and easiest way to use a dictionary, if I have to I'll implement a string key and use setValue:forKey: instead but I'd rather use the object key if I can.

like image 409
dnatoli Avatar asked May 24 '11 06:05

dnatoli


1 Answers

Dictionary keys are always copied. So you simply need to implement the NSCopying protocol for your class, which is just the copyWithZone: method.

Additionally you should implement the isEqual: method for your class.

Edit: How to implement your copyWithZone: depends on a number of factors (main factor: deep vs. shallow copy). See Apple's Implementing Object Copy guide and this SO answer.

like image 120
DarkDust Avatar answered Nov 08 '22 01:11

DarkDust