我需要在NSUserDefaults中保存一個NSMutableDictionary。我在網上搜索了很多例子,但沒有收到足夠相關的例子。有人可以發佈一小段代碼來關閉NSUserDefaults中的NSMutableDictionary,並在應用程序啓動時檢索它嗎?你也可以告訴我在哪裏放置代碼。NSUserDefaults幫助
我自己有一些代碼,但它不工作。
appDelegate.h - 數據
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *dat = [defaults objectForKey:@"theKey"];
tmpArray = [[NSMutableArray alloc] init];
tmpArray = [NSKeyedUnarchiver unarchiveObjectWithData:dat];
[self.window makeKeyAndVisible];
[window addSubview:tabBarController.view];
return YES;
}
appDelegate.h檢索 - 數據
- (void)applicationWillTerminate:(UIApplication *)application {
[self saveContext];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *dat = [NSKeyedArchiver archivedDataWithRootObject:tmpArray];
[defaults setObject:dat forKey:@"theKey"];
}
是的,它是爲一個陣列的存儲,但我將需要一個用於的NSMutableDictionary。
我覺得問題不在於NSUserDefaults。可能是您放置代碼的地方可能無法爲您保存數據。你可以發佈整個appDelegate方法嗎?你也可以放一個斷點,看看NSMutableDictionary是否保存在NSUserDefaults中? – 2011-03-26 06:43:38