Question

I have an NSDictionary object that is populated by NSMutableStrings 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.

Was it helpful?

Solution

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];

OTHER TIPS

Try using NSMutableDictionary, instead.

You can create a copy of the dictionary, filtering the keys as you go. I do this for converting between camel-case and underscores when populating objects from JSON using KVC. See my refactoring library, es_ios_utils, for source. ESNSCategories.h provides:

@interface NSMutableDictionary(ESUtils)
    //Changes keys using keyFilter. If keyFilter generates duplicate non-unique keys, objects will be overwritten.
    -(void)addEntriesFromDictionary:(NSDictionary*)d withKeyFilter:(NSString*(^)(NSString*))keyFilter;
...

So to make all keys upper case, you could do something like:

NSMutableDictionary *md = [NSMutableDictionary dictionaryWithCapacity:oldDictionary.count];
[md addEntriesFromDictionary:oldDictionary
               withKeyFilter:^NSString*(NSString *key) { 
                                 return key.uppercaseString;
                             }];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top