本文介绍了更改 NSDictionary 中的键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法可以返回一个带有特定键和值的 nsdictionary.我需要将字典中的键名更改为新的键名,但该键的值需要相同,但我被困在这里.需要帮助
I have a method which returns me a nsdictionary with certain keys and values. i need to change the key names from the dictionary to a new key name but the values need to be same for that key,but i am stuck here.need help
推荐答案
此方法仅适用于可变字典.如果新密钥已经存在,它不会检查应该做什么.
This method will only work with a mutable dictionary. It doesn't check what should be done if the new key already exists.
你可以通过调用 mutableCopy 来获取一个不可变的可变字典.
You can get a mutable dictionary of a immutable by calling mutableCopy on it.
- (void)exchangeKey:(NSString *)aKey withKey:(NSString *)aNewKey inMutableDictionary:(NSMutableDictionary *)aDict
{
if (![aKey isEqualToString:aNewKey]) {
id objectToPreserve = [aDict objectForKey:aKey];
[aDict setObject:objectToPreserve forKey:aNewKey];
[aDict removeObjectForKey:aKey];
}
}
这篇关于更改 NSDictionary 中的键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!