2013-03-06 82 views
0

在我的第一個函數中,我創建了一個NSMutableDictionary並將其保存在一個數組中。MutableDictionary變得不可變

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]]; 
NSMutableDictionary *tempPlayerDictArray = [[NSMutableDictionary alloc] init]; 

if (!(userDeviceName)) { 
    [tempPlayerDictArray setValue:userDeviceName forKey:@"DeviceName"]; 
}else{ 
    [tempPlayerDictArray setValue:@"empty" forKey:@"DeviceName"]; 
} 
[tempPlayersArray addObject:tempPlayerDictArray]; 

[defaults setObject:tempPlayersArray forKey:@"kgpsTempArray"]; 
[defaults synchronize]; 

在我的第二個函數中,我把它作爲NSCFDictionary - 這是不可變的。

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]]; 
NSMutableDictionary *dictionaryForSearching = [[NSMutableDictionary alloc] init]; 
NSLog(@"%@",[dictionaryForSearching class]); 

dictionaryForSearching = [tempPlayersArray objectAtIndex:index]; 

NSLog(@"%@",[[tempPlayersArray objectAtIndex:index] class]); 
NSLog(@"%@",[dictionaryForSearching class]); 

第一個日誌顯示「NSDictionaryM」。
第二個日誌顯示「NSCFDictionary」。
而第三個顯示「NSCFDictionary」以及...

任何人都可以解釋我爲什麼?以及如何解決它?

回答

4

NSUserDefaults適用於不可變對象,所以這就是當您返回字典時它被更改的原因。

你可以試試這個:

dictionaryForSearching = [[NSMutableDictionary alloc] initWithDictionary:[tempPlayersArray objectAtIndex:index]]; 
+0

非常感謝! – 2013-03-06 11:11:24

0

是,NSUserDefaults是自由複製,堅持和反序列化,因爲它喜歡。假定它不返回可變對象。如果您需要一個可變對象,請製作一個可變副本。

0

每一件事情取決於從這裏:

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]]; 

NSUserDefaults的閱讀總是給你不可變對象。