更改嵌套 NSMutableDictionary 中的值
Change value in a nested NSMutableDictionary
我有一个 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" 从 "published" 更改为 "reserved"?
谢谢!
假设 dictionary
和 cardInfo
都是 NSDictionary
个实例:
您可以获得嵌套字典的可变副本,修改适当的值,然后将修改后的字典写回 "top level" 字典,如下所示:
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;
我有一个 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" 从 "published" 更改为 "reserved"?
谢谢!
假设 dictionary
和 cardInfo
都是 NSDictionary
个实例:
您可以获得嵌套字典的可变副本,修改适当的值,然后将修改后的字典写回 "top level" 字典,如下所示:
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;