Search code examples
swiftnsobjectnscoding

Implement NSCoding on NSObject


I got these errors on NSObject class only. UIButton and UILabel have no such error.

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] ?? []
    }

} 

Any ideas?

NSCoding error


Solution

  • NSCoding (and Codable which I think you should be using instead) is a protocol so you are not overriding anything so remove override and any calls to 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] ?? []
    }