无法将数据从NSKeyedUnarchiver投射到对象

问题描述 投票:0回答:2

我将对象归档到数据中,并通过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 ")
            }
swift nscoding nskeyedarchiver nskeyedunarchiver
2个回答
0
投票

您的错误在这里:

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

typo->名字


0
投票

编码时,您需要进入Objective-C世界:

    coder.encode(firstName as NSString // ...
    coder.encode(lastName as NSString // ...
    coder.encode(age as NSNumber // ...

现在您正在编码使用NSCoding的东西,一切都会好起来的。

© www.soinside.com 2019 - 2024. All rights reserved.