在AppDelegate.swift中,我有:
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}在状态恢复期间,iOS将调用我的encodeRestorableState() & decodeRestorableState()类方法。
关于状态恢复,Codable是如何工作的?iOS调用什么以及如何绑定我的可编码结构和类?
发布于 2018-10-26 03:24:05
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
}
}https://stackoverflow.com/questions/52995252
复制相似问题