在iOS 中通常会出现程序由于锁屏或者按了Home键,程序进入后台,当程序返回前台的时候,用户希望看到的仍然是之前操作的一些内容。,因而在程序的设计和开发过程中就要去开发者采取某种手段满足用户的这种需求。很欣慰的是Apple已经提供了针对该问题的解决方案,具体的步骤如下:
1、需要AppDelegate中实现两个方法:
- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
return YES;
}
- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
return YES;
}
这两个方法从6.0以后才能使用,API还提供了willEncodeRestorableStateWithCoder和didDecodeRestorableStateWithCoder两个方法。
2、需要为支持状态保存的UIViewController设置Restoration ID,如图:
有时候程序中可能未使用xib或者Storyboard,那么需要支持恢复的类中实现一些方法,基本原则如下:
- 类要遵循UIViewControllerRestoration协议;
- 实现viewControllerWithRestorationIdentifierPath方法
- 设置自己的·restorationIdentifier和restorationClass,
例如:
self.restorationIdentifier = @"AnyIdentifier";
self.restorationClass = [self class];
3、以上的操作只能保证当程序从后台返回到前台的时候对应的能够恢复到对应的页面,具体subView的状态恢复还需要实现以下方法:
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
//[coder encodeObject:AnyObject forKey:@“AnyKey"];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
//AnyObject = [coder decodeObjectForKey:@“AnyKey"];
[super decodeRestorableStateWithCoder:coder];
}
实现原理和归档是一样的