我有一个符合NSCoding协议的简单对象。
NSCoding
import Foundation class JobCategory: NSObject, NSCoding { var id: Int var name: String var URLString: String init(id: Int, name: String, URLString: String) { self.id = id self.name = name self.URLString = URLString } // MARK: - NSCoding required init(coder aDecoder: NSCoder) { id = aDecoder.decodeObject(forKey: "id") as? Int ?? aDecoder.decodeInteger(forKey: "id") name = aDecoder.decodeObject(forKey: "name") as! String URLString = aDecoder.decodeObject(forKey: "URLString") as! String } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(name, forKey: "name") aCoder.encode(URLString, forKey: "URLString") } }
我正在尝试将其实例保存在其中,UserDefaults但是由于以下错误,它一直失败。
UserDefaults
由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“试图为关键jobCategory插入非属性列表对象”
这是我要保存的代码UserDefaults。
enum UserDefaultsKeys: String { case jobCategory } class ViewController: UIViewController { @IBAction func didTapSaveButton(_ sender: UIButton) { let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com") let userDefaults = UserDefaults.standard userDefaults.set(category, forKey: UserDefaultsKeys.jobCategory.rawValue) userDefaults.synchronize() } }
我用普通字符串将枚举值替换为key,但是仍然发生相同的错误。知道是什么原因造成的吗?
您需要创建Data从您的实例JobCategory使用实例NSKeyedArchiver.archivedData(withRootObject:)和存储Data例如在UserDefaults使用后解除封存NSKeyedUnarchiver.unarchiveObject(with:),因此,尝试这样的。
Data
JobCategory
NSKeyedArchiver.archivedData(withRootObject:)
NSKeyedUnarchiver.unarchiveObject(with:)
用于将数据存储在UserDefaults
let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com") let encodedData = NSKeyedArchiver.archivedData(withRootObject: category, requiringSecureCoding: false) let userDefaults = UserDefaults.standard userDefaults.set(encodedData, forKey: UserDefaultsKeys.jobCategory.rawValue)
用于从中检索数据UserDefaults
let decoded = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as! Data let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! JobCategory print(decodedTeams.name)