I archive object to data and save it to disk success by NSKeyedArchiver, but when I get data from NSKeyedUnarchiver, I can't cast it to type Object. I try to do it in many ways, but none of them success. I hope you can help me to solve this problem.. here is my code:
class Person:
class Person: NSObject, NSCoding {
func encode(with coder: NSCoder) {
coder.encode(firstName, forKey: "fisrtName")
coder.encode(lastName, forKey: "lastName")
coder.encode(age, forKey: "age")
}
required convenience init?(coder: NSCoder) {
guard let firstName = coder.decodeObject(forKey: "firstName") as? String,
let lastName = coder.decodeObject(forKey: "lastName") as? String else {
return nil
}
let age = coder.decodeInteger(forKey: "age")
self.init(firstname: firstName, lastName: lastName, age: age)
}
let firstName: String
let lastName: String
let age: Int
init(firstname: String, lastName: String, age: Int) {
self.firstName = firstname
self.lastName = lastName
self.age = age
}
}
Save data to disk:
let tuan = Person(firstname: "Tuan", lastName: "Hoang", age: 21)
let directoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = directoryPath.first!.appendingPathComponent("PersonData")
let savePath = path.appendingPathComponent("data.plist")
do {
try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)
let data = try! NSKeyedArchiver.archivedData(withRootObject: tuan, requiringSecureCoding: false)
do {
try data.write(to: savePath)
print("Save data success")
} catch {
print("Cant save data to path + \(error.localizedDescription)")
}
} catch {
print("Cant not create directory + \(error.localizedDescription)")
}
Load data:
do {
let savedData = try Data.init(contentsOf: savePath)
print("Get data success")
guard let data = try? NSKeyedUnarchiver.unarchivedObject(ofClass: Person.self, from: savedData) else {
print("Cant cast data")
return
}
print(data?.firstName)
} catch {
print("Cant get saved data ")
}
your error is here:
coder.encode(firstName, forKey: "fisrtName")
typo -> firstName