您的位置:首页 > 移动开发 > IOS开发

iOS 应用状态恢复

2016-02-25 17:15 387 查看
在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,那么需要支持恢复的类中实现一些方法,基本原则如下:
1)类要遵循UIViewControllerRestoration协议;
2)实现viewControllerWithRestorationIdentifierPath方法
3)设置自己的·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];

}

//个人感觉是,实现原理和归档是一样的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: