更新时间:2023-10-19 13:22:28
您需要使用 archivedData(withRootObject:)
并存储该Data
UserDefaults
中的实例,然后使用 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)