I am having problems creating new keys for a Nested NSDictionary. Here's what I have done
I have this kind of NSMutableDictionary
NSMutableDictionary *Ga=[NSMutableDictionary dictionaryWithDictionary:@{@"Node1" :@{@"SubNode11" :@40,@"SubNode12":@30}}];
Which NSLogs as:
Node1 = {
SubNode11 = 40;
SubNode12 = 30;
};
Now to add another root key and a nested key I did this,
[Ga setObject:@{@"SubNode21" : @555} forKey:@"Node2"];
Now the NSLog outputs:
Node1 = {
SubNode11 = 40;
SubNode12 = 30;
};
Node2 = {
SubNode21 = 555;
};
}
I need to add another key to an existing Node, say SubNode22=345; for Node2 in a separate line of code, so I thought this might work
[[Ga objectForKey:@"Node2"] setObject:@5555 forKey:@"SubNode22"];
But this show Error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance"
I don't what the Problem is,, this method seems straight forward to me.. Any solution please.
The issue here is that the literal dictionary syntax (the
@{...}
syntax) produces anNSDictionary
--what you actually need is anNSMutableDictionary
. (TheNSDictionary
class is immutable; thesetObject:forKey:
method is only present in theNSMutableDictionary
subclass, which is why you're getting the exception.) To fix the problem, you'll need to do something likeThe 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 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 calledsetObject:ForKey:
because that is a method ofNSMutableDictionary
. Using Apples new literal dictionaries@{ key: object}
only creates immutable dictionaries.So what you actually need is to make sure you're created
NSMutableDictionary
s using either[NSMutableDictionary dictionaryWithObjectsAndKeys:];
or[@{ Key: Object } mutableCopy]
So here is your code changed
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: