【问题标题】:How to rewrite this encoding for a UISwitch and also how to decode it?如何为 UISwitch 重写此编码以及如何对其进行解码?
【发布时间】:2020-01-02 18:25:03
【问题描述】:

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

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

我收到了这个错误:

无法将“CodingKey.Protocol.Type”类型的值转换为预期的参数类型“String”

我该怎么办?

【问题讨论】:

  • 使用 UserDefaults 存储值..
  • forKey后面的参数必须是String,这就是错误告诉你的。

标签: swift encoding decoding state-restoration


【解决方案1】:

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

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)

【讨论】:

  • 请不要在UserDefaults 中使用value(forKey:)。有object(forKey:),对于这种情况func retrieveSwitchState() -> Bool { return userDefault.bool(forKey: "SOME_SWITCH_STATE") }
  • 那我们如何从中取回一个存储的值呢?
  • 你的意思是不要直接使用字符串。如果是这样的话,我这样做是为了可读性
  • 我的意思是使用bool(forKey,它返回Bool值或false,如果键不存在。
猜你喜欢
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 2019-10-04
  • 1970-01-01
相关资源
最近更新 更多