在 NSObject 上实现 NSCoding
Implement NSCoding on NSObject
我只在 NSObject class 上遇到这些错误。 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
(以及我认为您应该使用的 Codable
)是一个协议,因此您不会覆盖任何内容,因此删除 override
和对 [=14= 的任何调用]
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] ?? []
}
我只在 NSObject class 上遇到这些错误。 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
(以及我认为您应该使用的 Codable
)是一个协议,因此您不会覆盖任何内容,因此删除 override
和对 [=14= 的任何调用]
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] ?? []
}