我有一个符合NSCoding
的课程:
class Middleware : NSObject, NSCoding {
var name: String
var uri: String
// MARK: NSCoding
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
uri = aDecoder.decodeObject(forKey: "uri") as! String
}
func encode(with: NSCoder) {
with.encode(name, forKey: "name")
with.encode(uri, forKey: "uri")
}
}
在UserDefaults中存储该类失败:
userDefaults.set(Middleware(name: "Volkszaehler Demo", uri: "http://demo.volkszaehler.org/middleware.php"), forKey: "middlewares")
给出:
***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'尝试为关键中间件插入非属性列表对象'
答案 0 :(得分:1)
得到它 - 自定义对象需要首先通过编码器:
let encodedData = NSKeyedArchiver.archivedData(withRootObject: middleware)
然后可以存储encodedData。