开发者

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 p开发者_如何转开发rotected from being changed meaning it will always be the same unless I remove it and add another to the dictionary?

Thanks.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜