Skip to content

Instantly share code, notes, and snippets.

@pascalpp
Last active March 12, 2022 19:12
Show Gist options
  • Save pascalpp/b001e303e77677ff1223c1da27305a4f to your computer and use it in GitHub Desktop.
Save pascalpp/b001e303e77677ff1223c1da27305a4f to your computer and use it in GitHub Desktop.
Swift 5 extension to add NSColor support to 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
}
}
@pascalpp
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment