xcode - 设置嵌套对象的值



我有一个来自服务的json,我需要更改一个obeject的值。

 {
        question =     (
                    {
                answer =             (
                                    {
                        Id = 1;
                        value = 1;
                    },
                                    {
                        Id = 2;
                        value = 0;
                    }
                );
            },
    .....

我使用该代码直接访问第二个"value"元素并将其设置为"true"

 NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    NSMutableDictionary *preguntasDict = [[NSMutableDictionary alloc] init];
    preguntasDict      =[[[dict valueForKey:@"question"]mutableCopy];
    NSMutableDictionary *answer = [[NSMutableDictionary alloc] init];
    respuestasDict     =[[[[preguntasDict valueForKey:@"answer"]objectAtIndex:0]objectAtIndex:1] mutableCopy];
    [respuestasDict setObject:[NSNumber numberWithBool:true] forKey:@"value"];

它有效:"respuestasDict"会改变,但 whoole "dict"不会。

我的问题是:如何重建整个字典?或者可以直接访问嵌套对象并更改它?

请注意

perguntasDictrespuestasDict是字典的可变副本,因此基本上您正在编辑dict的副本。您需要直接访问dict,如下所示:

NSArray *answers = dict[@"question"][@"answer"];
[answers firstObject][@"value"] = @(YES);

PS:做字典[@"问题"]和[dict objectForKey:@"question"]是一回事。此外,@(YES)[NSNumber numberWithBool:true]是一回事

最新更新