centree
centree

Reputation: 2439

NSMutableDictionary setObject forKey forKey...etc

I'm trying to setObjects that are deep in my NSMutableDictionary, by that I mean there are a few levels of keys before I can get to them.

Obviously I can't do

setObject:x forKey forKey forKey forKey...

How can I achieve that?

Upvotes: 1

Views: 608

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70966

Use key-path coding. Something like:

[myDictionary setValue:newValue forKeyPath:@"foo.bar.baz"];

That looks up foo on myDictionary, then takes whatever it gets and looks up bar on that, then takes whatever it gets that time and calls setValue:forKey: on that to assign a new value for baz. You can also use key paths to look up values:

id currentValue = [myDictionary valueForKeyPath:@"foo.bar.baz"];

Upvotes: 6

Paul.s
Paul.s

Reputation: 38728

You would just do something like

mutableDictionary[key1][key2][key3] = value;

BUT this multi nesting of dictionaries is most likely hinting at a bigger problem with your design.

Upvotes: 6

Related Questions