gpt4 book ai didi

ios - 更改嵌套 NSMutableDictionary 中的值

转载 作者:行者123 更新时间:2023-11-29 10:23:53 25 4
gpt4 key购买 nike

我有一个 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"]];

如何将对象“状态”从“已发布”更改为“保留”?

谢谢!

最佳答案

假设 dictionarycardInfo 都是 NSDictionary 实例:

您可以获得嵌套字典的可变副本,修改适当的值,然后将修改后的字典写回“顶级”字典,如下所示:

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

我猜你可以将它压缩成一行,但这将是一行丑陋的。

编辑:

如果外部和内部字典都已经是可变的,那当然会稍微简化一些事情:

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

关于ios - 更改嵌套 NSMutableDictionary 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com