Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change an NSDictionary's key?

I have an NSDictionary object that is populated by instances of NSMutableString for its keys and objects. I have been able to change the key by changing the original NSMutableString with the setString: method. They key however remains the same regardless of the contents of the string used to set the key initially.

My question is, is the key protected from being changed meaning it will always be the same unless I remove it and add another to the dictionary?

Thanks.

like image 248
Mark Reid Avatar asked Dec 10 '22 16:12

Mark Reid


2 Answers

The keys are -copy'd when the items are set, so you can't changing it afterwards is useless.

Methods that add entries to dictionaries—whether as part of initialization (for all dictionaries) or during modification (for mutable dictionaries)—copy each key argument (keys must conform to the NSCopying protocol) and add the copies to the dictionary. Each corresponding value object receives a retain message to ensure that it won’t be deallocated before the dictionary is through with it.

You could use CFDictionary with kCFTypeDictionaryKeyCallBacks, or just replace the item:

id value = [dictionary objectWithKey:oldKey];
[dictionary setObject:value withKey:newKey];
[dictionary removeObjectForKey:oldKey];
like image 57
kennytm Avatar answered Dec 30 '22 14:12

kennytm


Try using NSMutableDictionary, instead.

like image 41
Alex Reynolds Avatar answered Dec 30 '22 12:12

Alex Reynolds