我的自定义对象符合以下 NSCoding 协议的方法
required init(coder decoder: NSCoder) {
super.init()
createdDate = decoder.decodeObject(forKey: "created_date") as? Date
userId = decoder.decodeInteger(forKey: "user_id")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(createdDate, forKey: "created_date")
aCoder.encode(userId, forKey: "user_id")
}
这是Swift 3中NSCoding协议的正确方法名,但应用程序崩溃并出现错误
SwiftValue encodeWithCoder - unrecognized selector sent to instance
显然,该方法不可用,那么为什么它没有被识别?参考:https://developer.apple.com/reference/foundation/nscoding 这是我创建的归档器方法。
func encodeObject(_ defaults:UserDefaults, object:NSCoding?, key:String) {
if (object != nil) {
let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object)
defaults.set(encodedObject, forKey: key)
} else {
defaults.removeObject(forKey: key)
}
}