iOS应用状态保存和恢复

当应用被后台Kill掉的时候希望从后台返回的时候显示进入后台之前的内容

 

在Appdelegate中设置

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder{
    return YES;
}
- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder{
    return YES;
}

 为每个ViewController设置:restorationIdentifier(可以直接在sb中设置),restorationClass

     如果设置了restorationClas则必须遵守UIViewControllerRestoration协议返回恢复时的控制器

+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray<NSString *> *)identifierComponents coder:(NSCoder *)coder{
    UIStoryboard *storybord = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController *controller = [storybord instantiateViewControllerWithIdentifier:@"mywebcontroller"];
     controller.restorationIdentifier = [identifierComponents lastObject];
    controller.restorationClass = [MyWebViewController class];
    return controller;
}

如果未指定代理方法则从Appdelgate中的代理中返回

If a view controller has an associated restoration class, the viewControllerWithRestorationIdentifierPath:coder: method of that class is called during state restoration. That method is responsible for returning the view controller object that matches the indicated view controller. If you do not specify a restoration class for your view controller, the state restoration engine asks your app delegate to provide the view controller object instead.

在控制器中保存和恢复状态

//只保存状态,如果是数据的话保存在文件中如NSUserdefault等
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder{
    //保存开关状态
    [coder encodeBool:_switchBtn.isOn forKey:@"ison"];
    
    [super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder{
    [super decodeRestorableStateWithCoder:coder];
    //获取开关状态
    _switchBtn.on = [coder decodeBoolForKey:@"ison"];
    
}

 

转载于:https://www.cnblogs.com/cnman/p/10803043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值