首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Codable如何适应iOS恢复过程?

Codable如何适应iOS恢复过程?
EN

Stack Overflow用户
提问于 2018-10-26 01:45:56
回答 1查看 299关注 0票数 1

AppDelegate.swift中,我有:

代码语言:javascript
复制
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
    return true
}

在状态恢复期间,iOS将调用我的encodeRestorableState() & decodeRestorableState()类方法。

关于状态恢复,Codable是如何工作的?iOS调用什么以及如何绑定我的可编码结构和类?

EN

回答 1

Stack Overflow用户

发布于 2018-10-26 03:24:05

encodeRestorableState(with:)向您传递一个NSCoder实例。恢复状态所需的任何变量都必须在这里使用encode(_:forKey:)和此编码器进行编码,因此必须符合Codable。

decodeRestorableState(with:)将这个相同的编码器传递到函数体中。您可以使用编码时使用的密钥访问解码器中的属性,然后将它们设置为实例变量,或者使用它们来配置控制器。

例如:

代码语言:javascript
复制
import UIKit

struct RestorationModel: Codable {
   static let codingKey = "restorationModel"
   var someStringINeed: String?
   var someFlagINeed: Bool?
   var someCustomThingINeed: CustomThing?
}

struct CustomThing: Codable {
   let someOtherStringINeed = "another string"
}

class ViewController: UIViewController {
   var someStringIDoNotNeed: String?
   var someStringINeed: String?
   var someFlagINeed: Bool?
   var someCustomThingINeed: CustomThing?

   override func encodeRestorableState(with coder: NSCoder) {
      super.encodeRestorableState(with: coder)
      let restorationModel = RestorationModel(someStringINeed: someStringINeed,
                                              someFlagINeed: someFlagINeed,
                                              someCustomThingINeed: someCustomThingINeed)

      coder.encode(restorationModel, forKey: RestorationModel.codingKey)
   }

   override func decodeRestorableState(with coder: NSCoder) {
      super.decodeRestorableState(with: coder)
      guard let restorationModel = coder.decodeObject(forKey: RestorationModel.codingKey) as? RestorationModel else {
         return
      }
      someStringINeed = restorationModel.someStringINeed
      someFlagINeed = restorationModel.someFlagINeed
      someCustomThingINeed = restorationModel.someCustomThingINeed
   }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52995252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档