2013-06-26 38 views
0

我正在尝试构建一个字典,其中包含字典(最终我希望转换为JSON)。问题在于我在构建它时遇到问题。将可变字典添加到可变字典中以转换为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); 

日志会希望阅读sendText

的第一部字典建立正常,但只要我努力,并与EXC_BAD_ACCESS

添加到第二个T弃暗投明

我认为这是一个内存寻址问题,因为它们都是可变的,但我不知道,也许nestedList不应该是可变的。任何帮助赞赏。

最终我想将其转换为JSON;

{ 
    "Basic": 
    { 
     "menuHeight":"46", 
     "menuMethod":"editText", 
     "menuOption":"1", 
    }, 
    "Pro": 
    {  
     "menuHeight":"96", 
     "menuMethod":"sendText", 
     "menuOption":"1", 
    } 
} 

回答

2

答: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 }; 
+0

完美的感谢。这读起来也好多了...... JSON上的错字很好地被发现了。 –

+0

不客气。 –