我正在尝试构建一个字典,其中包含字典(最终我希望转换为 JSON)。问题是我在构建它时遇到问题。
到目前为止,我已经有了这个,它应该做的是构建一个带有键的小字典并将其添加到一个较大的字典中,重置并加载小字典,然后将其添加到大字典中。
NSMutableDictionary *nestedList = [[NSMutableDictionary alloc]init];
NSMutableDictionary *nestedSections = [[NSMutableDictionary alloc] init];
[nestedList addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:46], @"menuHeight",
@"editText", @"menuMethod",
[NSNumber numberWithInt:1], @"menuOption",
nil]];
[nestedSections addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
nestedList, "@Basic",
nil]];
[nestedList removeAllObjects];
[nestedList addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:92], @"menuHeight",
@"sendText", @"menuMethod",
[NSNumber numberWithInt:1], @"menuOption",
nil]];
[nestedSections addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
nestedList, "@Pro",
nil]];
然后我希望这样解决;
NSString *string = [[nestedSections objectForKey:@"Pro"] objectForKey:@"menuMethod"];
NSLog(@"Method is : %@", string);
Log希望读取sendText
第一个字典构建得很好,但是当我尝试将其添加到第二个字典时,EXC_BAD_ACCESS 就崩溃了
我认为这是一个内存寻址问题,因为它们都是可变的,但我不确定,也许nestedList不应该是可变的。任何帮助表示赞赏。
最终我想将其转换为 JSON;
{
"Basic":
{
"menuHeight":"46",
"menuMethod":"editText",
"menuOption":"1",
},
"Pro":
{
"menuHeight":"96",
"menuMethod":"sendText",
"menuOption":"1",
}
}
最佳答案
A. NSMutableDictionary
不复制值(仅复制键)。因此,您添加相同的字典两次,并在删除对象等时更改两者(= 一个)。除此之外,在示例 JSON 中,数字看起来像字符串而不是数字。我认为这是一个错字。
B.添加现代 Objective-C 以获得更好的可读性,它应该如下所示:
NSDictionary *basicDictionary =
@{
@"menuHeight" : @46,
@"menuMethod" : "editText",
@"menuOption : @1
}
NSDictionary *proDictionary =
@{
@"menuHeight" : @96,
@"menuMethod" : "sendText",
@"menuOption : @1
}
NSDictionary *nestedSections = @{ @"Pro" : proDictionary, @"Basic" : basicDictionary };
关于xcode - 将可变字典添加到可变字典以转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320911/