在swift中将NSData解压缩回NSColor

时间:2015-01-30 18:55:01

标签: macos swift nsuserdefaults nsdata nscolor

我已经存档NSColor以将其存储在NSUserDefaults中:

var data = NSArchiver.archivedDataWithRootObject(NSColor.redColor())
storage.setObject(data, forKey: "color")
storage.synchronize()

但现在我需要从NSData获取颜色,我不知道该怎么做

2 个答案:

答案 0 :(得分:4)

你只需要使用if to towrap你的NSData,你还需要一个条件转换如下:

编辑/更新:

Swift 3或更高版本

// archiving
let color: NSColor = .red
let data = NSKeyedArchiver.archivedData(withRootObject: color)
UserDefaults.standard.set(data, forKey: "color")

// unarchiving 
if let loadedData = UserDefaults.standard.data(forKey: "color"), 
    let loadedColor =  NSKeyedUnarchiver.unarchiveObject(with: loadedData) as? NSColor {
    // you can access loadedColor here
    print(loadedColor)  // "sRGB IEC61966-2.1 colorspace 1 0 0 1\n"
}

答案 1 :(得分:0)

尝试使Leo的答案在Swift 5中工作时遇到一些错误。出现了此扩展,该扩展允许UserDefaults存储和检索颜色。尝试将其粘贴到游乐场中。

import Cocoa

extension UserDefaults {

    func set(_ color: NSColor, forKey: String) {
        if let data = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) {
            self.set(data, forKey: forKey)
        }
    }

    func color(forKey: String) -> NSColor? {
        guard
            let storedData = self.data(forKey: forKey),
            let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: storedData),
            let color = unarchivedData as NSColor?
        else {
            return nil
        }

        return color
    }

}

// get defaults instance
let defaults = UserDefaults.standard

// create a color
let mycolor = NSColor(red: 0.0, green: 0.5, blue: 0.8, alpha: 0.5)

// save the color
defaults.set(mycolor, forKey: "mycolor")

// read the color back. this returns an optional, may be nil
defaults.color(forKey: "mycolor")