在AppDelegate.swift
中,我有:
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
iOS 将在状态恢复期间调用我的encodeRestorableState()
&decodeRestorableState()
类方法。
Codable
在国家恢复方面如何运作?iOS 调用什么以及如何绑定我的可编码结构和类?
encodeRestorableState(with:( 会传递一个 NSCoder 实例。恢复状态所需的任何变量都必须在此处使用此编码器使用 encode(_:forKey:( 进行编码,因此必须符合 Codable。
decodeRestorableState(with:( 将你这个相同的编码器传递到函数体中。您可以使用编码时使用的密钥访问解码器中的属性,然后将其设置为实例变量或以其他方式使用它们来配置控制器。
例如
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
}
}