且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试在 Swift 3 中保存自定义对象时尝试插入非属性列表对象

更新时间:2023-10-19 13:22:28

您需要使用 archivedData(withRootObject:) 并存储该DataUserDefaults 中的实例,然后使用 unarchiveTopLevelObjectWithData(_:),所以试试这个.

You need to create Data instance from your JobCategory instance using archivedData(withRootObject:) and store that Data instance in UserDefaults and later unarchive using unarchiveTopLevelObjectWithData(_:), So try like this.

用于在 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.unarchiveTopLevelObjectWithData(decoded) as! JobCategory
print(decodedTeams.name)