我正在编写一个与联系人一起使用的应用程序,并尝试使用 UserDefaults 保存信息,但我得到了 SIGABRT。这是我的代码,我做错了什么?
class Contact{
var name = String()
var phone = String()
init(name: String, phone: String){
self.name=name
self.phone=phone
}
required init(coder decoder: NSCoder){
self.name = (decoder.decodeObject(forKey: "name") as? String)!
self.phone = (decoder.decodeObject(forKey: "phone") as? String)!
}
func encode(with coder: NSCoder){
coder.encode(name, forKey: "name")
coder.encode(phone, forKey: "phone")
}
}
在 ViewDidLoad 中创建联系人只是为了测试:
let userDefaults = UserDefaults.standard
var contactDictionary = Dictionary<String, [Contact]>()
override func viewDidLoad() {
super.viewDidLoad()
contactDictionary["A"] = [Contact(name: "Annabel",phone: "000")]
let encodedData = NSKeyedArchiver.archivedData(withRootObject: contactDictionary)
userDefaults.set(encodedData, forKey: "contactDictionary")
userDefaults.synchronize()
if let data = userDefaults.data(forKey: "contactDictionary"){
print("yep")
contactDictionary = (NSKeyedUnarchiver.unarchiveObject(with: data) as? [String : [Contact]])!
}
else{
print("nope")
}
}