我有一个NSMutableDictionary我想要更改元素的值。
//My dictionary:
{
objectId = 8ED998yWd1;
cardInfo = {
state = published; //THIS!
price = 40;
color = red;
}
};
我尝试了几种方法,但价值不会改变,如下所示:
[dictionary setObject:@"reserved" forKey:@"state"]; //nope
或者这个:
[dictionary setValue:@"reserved" forKeyPath:@"cardInfo.state"]; //nope
或那:
[[dictionary objectForKey:@"cardInfo"] setObject:@"reserved" forKey:@"state"]; //no
和此:
[dictionary setObject:@"reserved" forKey:[[dictionary objectForKey:@"cardInfo"] objectForKey:@"state"]];
如何将对象“state”从“已发布”更改为“已保留”?
谢谢!
答案 0 :(得分:2)
假设dictionary
和cardInfo
都是NSDictionary
个实例:
您可以获得嵌套字典的可变副本,修改相应的值,并将修改后的字典写回“顶级”字典,如下所示:
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
NSMutableDictionary *innerDict = [dictionary[@"cardInfo"] mutableCopy];
innerDict[@"state"] = @"reserved";
mutableDict[@"cardInfo"] = innerDict;
dictionary = [mutableDict copy];
我猜你可以在一行中挤压它,但这将是一条难看的线。
修改强>
如果外部字典和内部字典都已经mutable
,那么可以简化一些事情,当然:
NSMutableDictionary *innerDict = dictionary[@"cardInfo"];
innerDict[@"state"] = @"reserved";
dictionary[@"cardInfo"] = innerDict;