Reputation: 1965
How can I change the key of an existing object in a NSMutableDictionary?
Upvotes: 2
Views: 1621
Reputation: 8345
You will have to remove the object from the original key and add it back with the new key. You could turn this into a category on NSMutableDictionary
.
The category would look something like this:
@interface NSMutableDictionary (RenameKey)
- (void)renameKey:(NSString *)original to:(NSString *)new;
@end
@implementation NSMutableDictionary (RenameKey)
- (void)renameKey:(id)original to:(id)new; {
id value = [self objectForKey:original];
[self removeObjectForKey:original];
[self setObject:value forKey:new];}
@end
You should probably add a pre/postfix to the method name to avoid future name conflicts in the runtime. The above is also not thread-safe, it takes three steps to perform the rename.
Upvotes: 3