Save/Get UIColor from UserDefaults

a 夏天 提交于 2019-12-10 21:56:34

问题


I need some help to load and read UIColor from UserDefaults.

I found a nice extension to do that:

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

}

But NSKeyedUnarchiver.unarchiveObject was deprecated recently, so i don't know how to get data from it.

Any suggestions? Thank you!


回答1:


In your code, simply replace 2 lines, i.e

Replace

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

with

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

//// Here you can use try? instead of try! and wrap it in if-let statement. Your choice.

and

Replace

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

with

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

Also, use Data instead of NSData in var colorData: NSData? ,i.e.

var colorData: Data?



回答2:


Simply do as do the deprecation messages tell you:

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


来源:https://stackoverflow.com/questions/52999953/save-get-uicolor-from-userdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!