我需要在 NSUserDefaults 中保存一个 NSMutableDictionary。我在网上搜索了很多例子,但没有收到任何足够相关的例子。有人可以发布一小段代码,在关闭时将 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。