【问题标题】:NSKeyedUnarchiver.unarchiveTopLevelObjectWithData crashing when data value is nil当数据值为 nil 时,NSKeyedUnarchiver.unarchiveTopLevelObjectWithData 崩溃
【发布时间】:2019-04-30 01:21:17
【问题描述】:

我正在使用 Xcode 10.2.1、iOS 12.1+、Swift 5

下面的函数应该读取一个归档值并返回它。 您可以看到以前的代码(unarchiveObject)在被弃用之前一直有效。

只要 'data' 的返回值不为零,代码就可以工作 - 这意味着之前已经保存了一个值。 但是,在新安装的应用程序中,这会崩溃,因为之前没有保存该值。

致命错误:在展开可选值时意外发现 nil

由于我不想预加载值,编写此函数以使其不会崩溃的正确方法是什么?

(似乎 NSKeyedUnarchiver.unarchiveTopLevelObjectWithData 现在也已在 iOS 12+ 中被弃用。正确的替代品是什么?)

func color(forKey defaultName: String) -> UIColor? {
    var color: UIColor?
    // Working code prior to Swift 5 and iOS 12
    //        if let colorData = data(forKey: defaultName) {
    //            color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
    //        }

    // Works unless NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data(forKey: defaultName)!) returns nil
    do {
        if let colorData = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data(forKey: defaultName)!) as? UIColor {
            color = colorData
        }
    } catch {
        //print("Couldn't read file.")
    }
    return color
}

【问题讨论】:

  • 您可以像解决任何不应强制解包的可选选项一样解决它。
  • 抱歉,但我不确定这对于作为 UIColor 的类型数据如何工作 - 你能更具体一点吗?

标签: ios swift


【解决方案1】:

首先在这种情况下替换unarchiveObject(with:)unarchivedObject(ofClass:from:)

其次,只需执行与 Swift 5 和 iOS 12 之前的工作代码中相同的可选绑定

func color(forKey defaultName: String) -> UIColor? {
    guard let colorData = data(forKey: defaultName) else { return nil }
    return try? NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
}

【讨论】:

  • 如果我用 'unarchivedObject' 替换,我是否还有要处理的弃用?
  • @wayneh 不,unarchivedObject(ofClass:from:) 没有被弃用,恰恰相反,它是现代方式。你问什么是正确的替代品,你被告知了答案。
  • @matt - 我发现这个页面表明它已被弃用(或者我读错了?)developer.apple.com/documentation/foundation/nskeyedarchiver/…
  • 你确实读错了。您已获得 vadian 答案中的链接。点击它!
  • @matt - 呃! :)
猜你喜欢
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2023-04-04
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2011-12-19
相关资源
最近更新 更多