在 swift 中将 NSData 解档回 NSColor

Unarchive NSData back to NSColor in swift

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

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

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

你只需要使用 if let 来解包你的 NSData 并且你还需要一个条件转换如下:

edit/update:

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

运行 尝试让 Leo 的答案在 Swift 中工作时遇到一些错误 5. 想出了这个扩展,让 UserDefaults 存储和检索颜色。尝试将其粘贴到 Playground 中。

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