我的自定义对象符合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)
}
}
答案 0 :(得分:5)
问题是您正在尝试存档可选项。替换此行:
if (object != nil) {
使用:
if let object = object {