Adding keys to Nested NSDictionary

允我心安 提交于 2019-11-30 20:36:53

The problem here has nothing to do with nesting. It has to do with mutable verse immutable. If the dictionary isn't mutable you can't add to it.

The error message is telling you, that NSDictionary's don't have a method called setObject:ForKey: because that is a method of NSMutableDictionary. Using Apples new literal dictionaries @{ key: object} only creates immutable dictionaries.

So what you actually need is to make sure you're created NSMutableDictionarys using either [NSMutableDictionary dictionaryWithObjectsAndKeys:]; or [@{ Key: Object } mutableCopy]

So here is your code changed

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"];

You can still use some of the new subscripting features though. For instance you can change the code to something like this thats more readable doing the same things:

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;

The problem is that your outer dictionary is an NSMutableDictionary, but your inner ones (the ones created with just the @{} syntax) are immutable NSDictionaries. You'll need to explicitly make them all mutable.

The issue here is that the literal dictionary syntax (the @{...} syntax) produces an NSDictionary--what you actually need is an NSMutableDictionary. (The NSDictionary class is immutable; the setObject:forKey: method is only present in the NSMutableDictionary subclass, which is why you're getting the exception.) To fix the problem, you'll need to do something like

[Ga setObject:[NSMutableDictionary dictionaryWithDictionary:@{@"SubNode21" : @555}]
       forKey:@"Node2"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!