如何将NSDictionary转换为NSMutableDictionary?

45

我有一个现有的NSDictionary,其中包含:

{
    "charts_count" = 2;
    "created_at" = "2010-04-12T16:37:32Z";
    exchange = NASDAQ;
    "followers_count" = 259;
    id = 8404;
    industry = "<null>";
    "messages_count" = 1436;
    ric = "GRPN.O";
    sector = "<null>";
    symbol = GRPN;
    title = Groupon;
    "updated_at" = "2011-09-05T04:17:56Z";
}

我该如何将这些内容取出并放入一个新的NSMutableDictionary中?


1
可能是重复的问题:将NSMutableDictionary变量设置为NSDictionary - jscs
4个回答

137

使用 -mutableCopy

NSDictionary *d;
NSMutableDictionary *m = [d mutableCopy];

请注意,-mutableCopy 返回 id(在 Swift 中为 Any),因此您需要将其分配/转换为正确的类型。它创建了原始字典的浅层副本。


3
需要翻译的内容:It should be noted that this will not inherently make the dictionary objects also mutable so if you have a dictionary of arrays of more dictionaries the children will not become mutable.请注意,这并不会使字典对象本身可变,因此如果您有一个包含更多字典数组的字典,那么其子级将不会变为可变。 - Vlad
@Vlad - 我想要实现你说的那样,需要使字典对象本身也可变,即字典的所有子对象都应该变为可变。 - Anand
@Vlad - 我想实现你所说的,拥有一个包含数组和其他字典的字典,并需要使所有子项固有可变。 - Anand

8

如果涉及Swift语言

var tempDic: NSMutableDictionary = yourDictionary.mutableCopy() as NSMutableDictionary

2

Try this in swift 3

let mutableDic: NSMutableDictionary =  (yourDictionary as! NSDictionary).mutableCopy() as! NSMutableDictionary

1
NSMutableDictionary *newInfo = [[NSMutableDictionary alloc] init];
[newInfo setDictionary:info];

由于你正在设置字典而不是追加,所以这也可以工作。你还可以使用:

[newInfo addEntriesFromDictionary:info];

为了达到相同的效果并追加到现有内容中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接