如何声明自定义对象,例如。编码类中的计时器

时间:2019-06-15 07:01:18

标签: ios json swift codable

我遇到了编码问题。我不明白如何在可编码类中初始化自定义计时器对象。

RecyclerView

或者我尝试这样做

    class ShelfItem: Codable {

      var objTimer = Timer()

但它向我显示了“类型'ShelfItem'不符合协议'可编码'”的错误

1 个答案:

答案 0 :(得分:0)

Timer对象进行编码/解码是没有意义的。

要从编码中排除objTimer,请在其他属性中添加CodingKeys,并省略objTimer

简单的示例(在大多数情况下,您甚至不需要上课)

struct ShelfItem : Codable {
    let name : String
    var timer : Timer

    private enum CodingKeys : String, CodingKey { case name }

    init(from decoder : Decoder) throws
    {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        timer = Timer()
    }
}