sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.87k stars 367 forks source link

Setting NSColor using NSData-archiver instead of keyed coder #129

Closed DivineDominion closed 7 years ago

DivineDominion commented 7 years ago

When I researched how to use Cocoa Bindings on macOS to create color picker preferences, I found this doc by Apple about archiving NSColor to user defaults:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DrawColor/Tasks/StoringNSColorInDefaults.html

The direct translation would be this:

extension UserDefaults {
    subscript(key: DefaultsKey<NSColor?>) -> NSColor? {
        get {
            guard let data = self.data(forKey: key._key) else { return nil }
            return NSUnarchiver.unarchiveObject(with: data) as? NSColor
        }
        set {
            guard let color = newValue else {
                self.setNilValueForKey(key._key)
                return
            }
            let data = NSArchiver.archivedData(withRootObject: color)
            self.setValue(data, forKey: key._key)
        }
    }
}

While the approach from the README works, too, and is consistent if you work with the subscript exclusively, maybe there are other cases like this that require an archiver instead of a coder.

@radex how do you think about this conceptually? Do you want to integrate stuff like this or let users figure that out?

radex commented 7 years ago

I haven't really dealt with NSArchiver before. What's the advantage/use of this over NSCoder?

DivineDominion commented 7 years ago

I shot too quick: after I dabbled with the available settings some more, I found that CocoaBindings can work with NSKeyedArchiver, too. That means the default archive/unarchive calls will do just fine 👍

Btw, NSArchiver seems to be the predecessor to NSKeyedArchiver. Both depend on NSCoding and are subclasses of NSCoder.