在NSObject上实施NSCoding

问题描述 投票:0回答:1

我仅在NSObject类上遇到这些错误。 UIButton和UILabel没有此类错误。

class Foo: NSObject, NSCoding {
    var title = ""
    var children: [Foo] = []



    // MARK: NSCoding
    override public func encode(with coder: NSCoder) {
        super.encode(with: coder)
        coder.encode(title as Any?, forKey: "title")
        coder.encode(children as Any?, forKey: "children")
    }

    required public init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        self.title = decoder.decodeObject(forKey: "title") as? String ?? ""
        self.children = decoder.decodeObject(forKey: "children") as? [Foo] ?? []
    }

} 

有什么想法吗?

NSCoding error

swift nsobject nscoding
1个回答
0
投票

NSCoding(和Codable)是一个协议,因此您不会覆盖任何内容,因此请删除override和对super的所有调用

public func encode(with coder: NSCoder) {
    coder.encode(title as Any?, forKey: "title")
    coder.encode(children as Any?, forKey: "children")
}

required public init?(coder decoder: NSCoder) {
    self.title = decoder.decodeObject(forKey: "title") as? String ?? ""
    self.children = decoder.decodeObject(forKey: "children") as? [Foo] ?? []
}
© www.soinside.com 2019 - 2024. All rights reserved.