Codable如何适应iOS还原过程?

时间:2018-10-25 17:45:56

标签: ios swift codable state-restoration

AppDelegate.swift中,我有:

func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
    return true
}

然后iOS会在状态恢复期间调用我的encodeRestorableState()decodeRestorableState()类方法。

Codable在状态恢复方面如何工作? iOS调用什么?如何绑定可编码的结构和类?

1 个答案:

答案 0 :(得分:1)

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

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

例如

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
   }
}
相关问题