无法更新使用NSUserDefauts值初始化的NSMutableDictionary

时间:2011-02-08 08:46:53

标签: iphone nsuserdefaults nsmutabledictionary

我使用NSUserDefaults来保存NSMutableDictionary。但是当我从NSUserDefaults中检索值时,我无法修改/更新我保存值的NSMutableDictionary的值。

需要一些关于如何做的建议吗?

2 个答案:

答案 0 :(得分:1)

您总是从NSDictionary获得NSUserDefaults的不可变实例。为了使它们变得可变,你需要做这样的事情:

dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"];
myMutableDict = [dict mutableCopy];
// Note that the retain count is +1, so you will need to
// release or autorelease myMutableDict later on.

答案 1 :(得分:0)

您也可以保存为plist。

这是你写一个plist的方式:

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDirectory = [paths objectAtIndex:0];
NSString * dataFilePath = [docDirectory stringByAppendingPathComponent:@"YourFile.dat"]

NSMutableDictionary * newLocalPlist = [[NSMutableDictionary alloc] init];

// add your prefs here

[newLocalPlist writeToFile:dataFilePath atomically:YES];
[newLocalPlist release];

这就是你从plist那里读到的:

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDirectory = [paths objectAtIndex:0];
NSString * dataFilePath = [docDirectory stringByAppendingPathComponent:@"YourFile.dat"]
NSMutableDictionary * lastLocalPlist = [[[NSMutableDictionary alloc] initWithContentsOfFile:dataFilePath] autorelease];