我使用NSUserDefaults來保存NSMutableDictionary。但是,當我從NSUserDefaults中檢索值時,我無法修改/更新要保存值的NSMutableDictionary的值。無法更新使用NSUserDefauts值初始化的NSMutableDictionary
需要一些建議如何做到這一點?
我使用NSUserDefaults來保存NSMutableDictionary。但是,當我從NSUserDefaults中檢索值時,我無法修改/更新要保存值的NSMutableDictionary的值。無法更新使用NSUserDefauts值初始化的NSMutableDictionary
需要一些建議如何做到這一點?
您總是從NSUserDefaults
獲得NSDictionary
的非可變實例。爲了使它們變得可變,你需要做這樣的事情:
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.
你也可以保存爲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];
非常感謝! :) +1 – Ratan 2011-02-08 08:59:25