2013-06-26 35 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

不客氣。 –