swift - 无法将数据从 NSKeyedUnarchiver 转换为对象

标签 swift nscoding nskeyedarchiver nskeyedunarchiver

我通过 NSKeyedArchiver 将对象归档到数据并将其成功保存到磁盘,但是当我从 NSKeyedUnarchiver 获取数据时,我无法将其转换为 Object 类型。我尝试了很多方法,但没有一个成功。我希望你能帮助我解决这个问题..这是我的代码:

:

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
    }
}

将数据保存到磁盘:

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)")
            }

加载数据:

    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 ")
            }

最佳答案

您的错误在这里:

    coder.encode(firstName, forKey: "fisrtName")

拼写错误 -> 名字

关于swift - 无法将数据从 NSKeyedUnarchiver 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58247021/

相关文章:

ios - UIImageview 上的 UITapGesture 不工作

ios - 带自动布局的侧边菜单

ios - 编码复杂对象 swift 3.0

arrays - 在设备上本地保存自定义类数组

ios - NSKeyedArchiver 在没有调用 -finishEncoding 的情况下被释放

swift - xcode - NavigationBarItem - 将图像更改为文本

ios - 为什么在设置框架时不能更改按钮高度?

ios - 序列化包含对核心数据中 NSManagedObjects 的引用的多维数组

swift - 如何存档具有关联值的枚举?

cocoa - NSImage 的动画在使用 NSKeyedArchiver 存档后丢失