Vins
Vins

Reputation: 1934

Change value in a nested NSMutableDictionary

I have a NSMutableDictionary to which I want to change the value of an element.

//My dictionary:

{
    objectId = 8ED998yWd1;
    cardInfo =     {
        state = published; //THIS!
        price = 40;
        color = red;
        }   
};

I have tried several ways, but the value does not change, like this:

[dictionary setObject:@"reserved" forKey:@"state"]; //nope

or this:

[dictionary setValue:@"reserved" forKeyPath:@"cardInfo.state"]; //nope

or that:

[[dictionary objectForKey:@"cardInfo"] setObject:@"reserved" forKey:@"state"]; //no

and this:

[dictionary setObject:@"reserved" forKey:[[dictionary objectForKey:@"cardInfo"] objectForKey:@"state"]];

How can I change the object "state" from "published" to "reserved"?

Thank you!

Upvotes: 3

Views: 1853

Answers (1)

Gamma
Gamma

Reputation: 1367

Assuming that both dictionary and cardInfo are NSDictionary instances:

You could get a mutable copy of the nested dictionary, modify the appropriate value, and write the modified dictionary back into the "top level" dictionary, like so:

NSMutableDictionary *mutableDict = [dictionary mutableCopy];
NSMutableDictionary *innerDict = [dictionary[@"cardInfo"] mutableCopy];
innerDict[@"state"] = @"reserved";
mutableDict[@"cardInfo"] = innerDict;
dictionary = [mutableDict copy];

I guess you could squeeze that in one line, but it would be one ugly line.

Edit:

If both the outer and inner dictionary were already mutable that would simplify things a bit, of course:

NSMutableDictionary *innerDict = dictionary[@"cardInfo"];
innerDict[@"state"] = @"reserved";
dictionary[@"cardInfo"] = innerDict;

Upvotes: 3

Related Questions