如何为 UISwitch 重写此编码以及如何对其进行解码?

How to rewrite this encoding for a UISwitch and also how to decode it?

我正在尝试保存一些开关的状态并在应用程序再次启动时恢复它,但是当我写这篇文章时:

override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)
    coder.encode(Int32(self.runSwitch1.state.rawValue), forKey: CodingKey.Protocol)
}

我收到这个错误:

Cannot convert value of type 'CodingKey.Protocol.Type' to expected argument type 'String'

我该怎么办?

如果您的意思不是在应用程序切换之间恢复状态,请针对要编码的类型提供唯一密钥

override func encodeRestorableStateWithCoder(coder: NSCoder) {
    coder.encode(self.runSwitch1.isOn, forKey: "switchState")    
  super.encodeRestorableStateWithCoder(coder)
}

//状态恢复后解码

override func decodeRestorableStateWithCoder(coder: NSCoder) {          
  super.decodeRestorableStateWithCoder(coder)
}

并通过

恢复开关状态
override func applicationFinishedRestoringState() {
   let restoredState =coder.decodeBool(forKey: "switchState") 
   self.switch.setOn(restoredState, animated: false)
}

即使在应用程序关闭后,也可以使用 CoreData 或其他基于数据库的框架来维持状态。或者你可以使用 userdefaults

class MySavedSwitchStates:NSObject {
    var userDefault = UserDefaults.standard
    private override init() {
    }
    static let shared = MySavedSwitchStates()

    //This saves state to preferences
    func setSwitchState(_ state:Bool) {
        userDefault.set(state, forKey: "SOME_SWITCH_STATE")
    }

    //This retrieve the current state of switch
    func retrieveSwitchState() -> Bool {    
        return userDefault.bool(forKey: "SOME_SWITCH_STATE")
    }
}

并在您的控制器中

//In your controller viewdidLoad
let restoredState = MySavedSwitchStates.shared.retrieveSwitchState()
self.switch.setOn(restoredState, animated: false)