1.看来了好几个例子,还是没搞清楚,每次app第一次运行都会 Warning: Unable to create restoration in progress marker file,并且第一次不会进入decodeRestorableStateWithCoder方法
2.这个不是我想实现的效果,我想实现每次程序后台和关闭的时候自动保存,然后程序启动的时候恢复,第一次也能正常
高洛峰2017-04-17 17:43:05
The state recovery function is not available on the simulator. It is not easy to test. There is no problem with the real machine. Go ahead and use it, boy.
Use NSUserDefaults instead:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//load status when starting
NSString * statusToRestore = [[NSUserDefaults standardUserDefaults] objectForKey:@"FightingStatus"];
NSDate *lastUpdated=[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdated"];
NSLog(@"restored:%@ on %@",statusToRestore,lastUpdated);
return YES;
}
-(void)applicationWillEnterForeground:(UIApplication *)application {
//restore status when reactive
NSString * statusToRestore = [[NSUserDefaults standardUserDefaults] objectForKey:@"FightingStatus"];
NSDate *lastUpdated=[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdated"];
NSLog(@"restored:%@ on %@",statusToRestore,lastUpdated);
}
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(nonnull NSCoder *)coder
{
return YES;
}
-(BOOL) application:(UIApplication *) application shouldRestoreApplicationState:(nonnull NSCoder *)coder
{
return YES;
}
-(void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(nonnull NSCoder *)coder
{
//
//[coder encodeFloat:2.0f forKey:@"Version"];
//NSLog(@"encode version :2.0f");
//save status when inactive
NSString * statusToSave=@"Fighting";
NSDate *lastUpdated = [NSDate dateWithTimeIntervalSinceNow:-3600];
[[NSUserDefaults standardUserDefaults] setObject:statusToSave forKey:@"FightingStatus"];
[[NSUserDefaults standardUserDefaults] setObject:lastUpdated forKey:@"LastUpdated"];
NSLog(@"saved:%@ on %@",statusToSave,lastUpdated);
}
-(void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder
{
//failed when testing in simulator
//NSLog(@"Version=%g",[coder decodeFloatForKey:@"Version"]);
}