如何在NSMutableDictionary中重命名密钥?

Emp*_*ack 11 iphone cocoa cocoa-touch objective-c

我有一个NSMutableDictionary.我必须Key在我的代码中动态地将字典中的任何内容重命名为新值.我找不到任何内置API来执行此操作.

我怎样才能做到这一点?是否有可用的内置API?

感谢大家..

bbu*_*bum 38

// assumes that olkdey and newkey won't be the same; they can't as
// constants... but...
[dict setObject: [dict objectForKey: @"oldkey"] forKey: @"newkey"];
[dict removeObjectForKey: @"oldkey"];
Run Code Online (Sandbox Code Playgroud)

想想"直接编辑现有密钥"的含义.字典是哈希; 它散列键的内容以查找值.

如果要更改密钥的内容会发生什么?密钥需要重新设置(字典的内部结构重新平衡)或者值不再可检索.

为什么要首先编辑密钥的内容?也就是解决上述问题的问题是什么?


nac*_*o4d 9

这应该工作:

- (void) renameKey:(id<NSCopying>)oldKey toKey:(id<NSCopying>)newKey{
    NSObject *object = [dictionary objectForKey:oldKey];
    [object retain];
    [dictionary removeObjectForKey:oldKey];
    [dictionary setObject:object forKey:newKey];
    [object release];
}
Run Code Online (Sandbox Code Playgroud)

这与bbum的答案完全相同,但是,如果你先删除旧密钥(就像在这个例子中那样),那么你必须暂时保留该对象,否则它可能会被解除分配;)

结论:除非你需要明确删除旧密钥,否则首先要做为bbum.


Cos*_*que 5

@interface NSMutableDictionary (KAKeyRenaming)
- (void)ka_replaceKey:(id)oldKey withKey:(id)newKey;
@end

@implementation NSMutableDictionary (KAKeyRenaming)
- (void)ka_replaceKey:(id)oldKey withKey:(id)newKey
{
    id value = [self objectForKey:oldKey];
    if (value) {
        [self setObject:value forKey:newKey];
        [self removeObjectForKey:oldKey];
    }
}
@end
Run Code Online (Sandbox Code Playgroud)

这也处理字典没有很好的键值的情况.