2012-05-31 69 views
0

我創建了兩個NSMutableDictionary:dictionary1和dictionary2。在第一個字典中,我存儲了一些有鍵的數組對象。而在第二字典我存儲第一庫的對象,像這樣的關鍵在於:從NSMutableDictionary獲取NSMutableDictionary裏面的值

int page = 1; 
[dictionary2 setObject:dictionary1 forKey:[NSString stringWithFormat:@"%d",page]]; 
[dictionary1 removeAllObjects]; 

但我不喜歡這樣

dictionary1 = [dictionary2 valueForKey:[NSString stringWithFormat:@"%d",page]]; 
NSLog(@"dictionary1 %@", dictionary1);` 

對象的檢索的時間,然後它給空值。我不知道我做了什麼錯誤。

回答

4

後添加dictionary1dictionary2,要刪除所有的對象。

這是字典2中的相同字典(它不創建副本),因此您也要從中刪除對象。您需要刪除行[dictionary1 removeAllObjects];

然後,因爲你是在這一點上與dictionary1做,你可以刪除對它的引用,或設置爲一個不錯的新閃亮的字典這是準備使用:

// Remove the reference 
dictionary1 = nil; 

// Or, create a new, empty dictionary 
dictionary1 = [[NSDictionary alloc] init]; 
+0

感謝。但首先,我想從dictionary1中移除所有對象,下一次我想將它們添加到dictionary1中。現在我能做什麼。 –

+0

只是使用:'dictionary1 = [[NSDictionary alloc] init];'而不是'removeAllObjects'將其設置爲一個新的字典,或'dictionary1 = nil;'然後創建新的字典,當你準備好使用它時第一次。 – lnafziger

0

您是否正確alloc/init dictionary1dictionary2?確保字典本身不是nil

0

試試這個

dictionary1 = [dictionary2 objectForKey:[NSString stringWithFormat:@"%d",page]];