我希望在应用程序终止时保存几个数组。我在app delegate中使用NSUserDefaults实现了这个。任何人都可以看看我的代码,看看有什么不对?它无论如何都无济于事。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
workouts = [NSMutableArray arrayWithObjects:nil];
menu = [NSMutableArray arrayWithObjects:@"Home",nil];
workoutNames = [NSMutableArray arrayWithObjects:nil];
routinesMade = [NSMutableArray arrayWithObjects:nil];
test = [NSMutableArray arrayWithObjects:nil];
defaults = [NSUserDefaults standardUserDefaults];
self.workouts = [defaults objectForKey:@"workouts"];
self.menu = [defaults objectForKey:@"menu"];
self.workoutNames = [defaults objectForKey:@"workoutNames"];
self.routinesMade = [defaults objectForKey:@"routinesMade"];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application
{
defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:workouts forKey:@"workouts"];
[defaults setObject:menu forKey:@"menu"];
[defaults setObject:workoutNames forKey:@"workoutNames"];
[defaults setObject:routinesMade forKey:@"routinesMade"];
[defaults synchronize];
}
顺便说一下,我在头文件中声明了默认值。多谢你们!
答案 0 :(得分:4)
我想我知道问题所在。您的代码位于applicationWillTerminate:
方法内。除非您明确设置应用程序不在后台运行(通过设置'应用程序不在后台运行'键),几乎可以肯定这个方法永远不会被调用,因为当它被系统终止时,它将会已被暂停。
在这种情况下,请考虑在applicationDidEnterBackground:
方法中保存所需的信息。
希望这有帮助!
答案 1 :(得分:0)
锻炼和自我锻炼是我正确的一个属性? 所以你创建数组
workouts = [NSMutableArray arrayWithObjects:nil];
然后用null覆盖它,因为[defaults objectForKey:@"workouts"]
包含null