【问题标题】:Can't cast Data from NSKeyedUnarchiver to Object无法将数据从 NSKeyedUnarchiver 转换为对象
【发布时间】:2019-10-05 09:29:56
【问题描述】:

我将对象归档为数据并通过 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 ")
            }

【问题讨论】:

  • 不要try?,抓住错误。
  • 你需要抓住错误,看看问题出在哪里
  • @vadian 它说:​​无法读取数据,因为当我尝试 unarchiverObject 时它的格式不正确..
  • requiringSecureCoding: false 这不是您问题的答案,但这是错误的。你应该采用 NSSecureCoding。
  • 感谢@matt。我意识到必须将类 Person 扩展到 NSSecureCoding。我有一个错字..

标签: swift nscoding nskeyedarchiver nskeyedunarchiver


【解决方案1】:

你的错误在这里:

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

错字->名字

【讨论】:

  • second 不是错误,是correct
  • 在代码中自己尝试一下 -> 如果你不强制转换,它会崩溃
  • decodeObject(forKey: "age") as! Int 崩溃,但decodeInteger(forKey: "age") 没有崩溃。我在几个项目中使用它
  • 你是对的,对不起,我在我的代码中改变了它......对不起。
猜你喜欢
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
相关资源
最近更新 更多