从UserDefaults保存/获取UIColor

时间:2018-10-26 00:50:15

标签: swift string uicolor userdefaults nskeyedunarchiver

我需要一些帮助来从UserDefaults加载和读取UIColor。

我发现一个很好的扩展名可以做到这一点:

extension UserDefaults {
 func colorForKey(key: String) -> UIColor? {
  var color: UIColor?
  if let colorData = data(forKey: key) {
   color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
  }
  return color
 }

 func setColor(color: UIColor?, forKey key: String) {
  var colorData: NSData?
   if let color = color {
    colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
  }
  set(colorData, forKey: key)
 }

}

但是最近不推荐使用NSKeyedUnarchiver.unarchiveObject,所以我不知道如何从中获取数据。

有什么建议吗? 谢谢!

2 个答案:

答案 0 :(得分:2)

在您的代码中,只需替换两行,即

替换

color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor

color = try! NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)

/////在这里,您可以使用try?代替try!并将其包装在if-let语句中。您的选择。

替换

colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?

colorData = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)

另外,在Data中使用NSData代替var colorData: NSData?,即

var colorData: Data?

答案 1 :(得分:1)

只需按照弃用消息告诉您的方式进行操作

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

    // But why an Option<UIColor> here?
    func setColor(color: UIColor?, forKey key: String) {
        if let color = color,
            let colorData = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)
        {
            set(colorData, forKey: key)
        }
    }
}