2014-11-25 35 views
-1

我有一個NSMutableDictionary稱爲stuff,結構是這樣的:如何設置/獲取多級字典中的值?

{ 
    "ThingStats" : { "Thing1" : { "stat1" : 12, 
            "stat2" : 21 } , 
        "Thing2" : { "stat1" : 4, 
            "stat2" : 15 } 
       } , 

    "OtherStuff" : {...} 
} 

除了ThingStats它可以在這一級有其他字典。

使用下標很容易得到Thing1'sstat1這樣的:

stat1 = stuff[@"ThingStats"][@"Thing1"][@"stat1"]; 

,並將其設置是這樣的:

stuff[@"ThingStats"][@"Thing1"][@"stat1"] = @13; 

這一切的偉大工程在密鑰存在。

第一個問題:如果ThingStats字典中不存在stuff但,什麼是讓結構開始的第一項ThingStats的最佳方式?例如,如果我只有值stat1stat2Thing1什麼是從空stuff字典如下所示的stuff字典落得最簡單的方法?假設stuff不會爲零。

{ "ThingStats" : { "Thing1" : { "stat1" : 12, "stat2" : 21 } } } 

第二個問題:後來,當我得到的數值爲stat1stat2Thing2什麼是添加這些值與這個結構最終的最佳方式:

{ 
    "ThingStats" : { "Thing1" : { "stat1" : 12, 
            "stat2" : 21 } , 
        "Thing2" : { "stat1" : 4, 
            "stat2" : 15 } 
        } 
} 

三問題:如果我想使用上述的下標技術爲stat設置一個新值,我必須先做這樣的事情,以確保密鑰一直存在於值中:

if (stuff[@"ThingStats"][@"Thing1"][@"stat1"]) { 
    stuff[@"ThingStats"][@"Thing1"][@"stat1"] = newValue; 
} else { 
    // add the new stat some other way 
} 
+0

你是什麼意思的「什麼是最好的方式來添加,最終與這個:」? – kezi 2014-11-25 00:45:51

+0

這只是對象 - 詞典和數組。要記住的是,用字面表達式創建的字典/數組是不可變的,如果你想修改字典/數組,它必須是可變的。 – 2014-11-25 00:47:04

+0

如果我找到你,用'[NSMutableDictionary dictionary]'創建一個新的字典。使用'myDict [@「keyValue」] = elementValue;'向它添加元素。只要繼續這樣做,直到結構完成。 – 2014-11-25 01:38:36

回答

0

我認爲正確的軌道上你。你的問題3回答你的第一個問題。對於你的第一個問題,你可以使用:

//Setup 
NSMutableDictionary *stuff = [NSMutableDictionary dictionary]; 

if (!stuff[@"ThingStats"]) { 
    stuff[@"ThingStats"] = [NSMutableDictionary dictionary]; 
    stuff[@"ThingStats"][@"Thing1"] = [NSMutableDictionary dictionary]; 
    stuff[@"ThingStats"][@"Thing2"] = [NSMutableDictionary dictionary]; 
} 

//Use 

stuff[@"ThingStats"][@"Thing1"][@"stat1"] = @12; 
stuff[@"ThingStats"][@"Thing1"][@"stat2"] = @21; 
stuff[@"ThingStats"][@"Thing2"][@"stat1"] = @4; 
stuff[@"ThingStats"][@"Thing2"][@"stat2"] = @15; 
+0

完美。謝謝。 – 2014-11-25 02:12:07