3

我正在编写一个与联系人一起使用的应用程序,并尝试使用 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")
    }
}
4

1 回答 1

2

您需要使您的类 NSCoding 兼容并从 NSObject 继承。将您的联系人声明更改为联系人类:NSObject, NSCoding {. 顺便说一句,有条件地强制在以后打开它是没有意义的。decoder.decodeObject(forKey: "name") as! String

class Contact: NSObject, NSCoding {
    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")
    }
}

测试:

let contactDictionary = ["A":[Contact(name: "Annabel",phone: "000")]]

let encodedData = NSKeyedArchiver.archivedData(withRootObject: contactDictionary)
UserDefaults.standard.set(encodedData, forKey: "contactDictionary")

if let data = UserDefaults.standard.data(forKey: "contactDictionary") {
    print("yep")
    let contactDictionary2 = NSKeyedUnarchiver.unarchiveObject(with: data) as! [String : [Contact]]
}
else{
    print("nope")
}
于 2017-12-15T23:13:45.737 回答