我在为嵌套的NSDictionary创建新密钥时遇到问题.这就是我所做的
我有这种NSMutableDictionary
NSMutableDictionary *Ga=[NSMutableDictionary dictionaryWithDictionary:@{@"Node1" :@{@"SubNode11" :@40,@"SubNode12":@30}}];
哪个NSLog为:
Node1 = { SubNode11 = 40; SubNode12 = 30; };
现在添加另一个根密钥和嵌套密钥我做了这个,
[Ga setObject:@{@"SubNode21" : @555} forKey:@"Node2"];
现在NSLog输出:
Node1 = { SubNode11 = 40; SubNode12 = 30; }; Node2 = { SubNode21 = 555; }; }
我需要向现有节点添加另一个密钥,比如SubNode22 = 345;对于Node2在一个单独的代码行中,所以我认为这可行
[[Ga objectForKey:@"Node2"] setObject:@5555 forKey:@"SubNode22"];
但这显示错误“由于未捕获的异常终止应用程序’NSInvalidArgumentException’,原因:’ – [__ NSDictionaryI setObject:forKey:]:无法识别的选择器发送到实例”
解决方法
这里的问题与嵌套无关.它与可变的诗歌不可变有关.如果字典不可变,则无法添加到字典中.
错误消息告诉您,NSDictionary没有名为setObject的方法:ForKey:因为这是NSMutableDictionary的方法.使用Apples新的文字词典@ {key:object}只能创建不可变的词典.
所以你真正需要的是确保你使用[NSMutableDictionary dictionaryWithObjectsAndKeys:]创建NSMutableDictionarys;或[@ {Key:Object} mutableCopy]
所以这是你的代码改变了
NSMutableDictionary *subNode = [NSMutableDictionary dictionaryWithObjectsAndKeys:@40,@"SubNode11",@30,@"SubNode12",nil]; NSMutableDictionary *Ga = [NSMutableDictionary dictionaryWithObjectsAndKeys:subNode,@"Node 1",nil]; [Ga setObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@555,@"SubNode21",nil] forKey:@"Node2"]; [[Ga objectForKey:@"Node2"] setObject:@5555 forKey:@"SubNode22"];
您仍然可以使用一些新的下标功能.例如,您可以将代码更改为类似的内容,以便在执行相同操作时更具可读性:
NSMutableDictionary *Ga = [NSMutableDictionary dictionary]; // Create SubNodes NSMutableDictionary *subNode1 = [NSMutableDictionary dictionary]; subNode1[@"SubNode11"] = @40; subNode1[@"SubNode12"] = @30; NSMutableDictionary *subNode2 = [NSMutableDictionary dictionary]; subNode2[@"SubNode21"] = @555; // Set SubNodes to Main Node Container Ga[@"Node1"] = subNode1; Ga[@"Node2"] = subNode2; // Set a nested subnode's value. Ga[@"Node2"][@"SubNode22"] = @5555;