1
1
mirror of https://github.com/danbee/persephone synced 2025-03-04 08:39:11 +00:00

Add observer helper method for prefs

This commit is contained in:
Daniel Barber 2019-02-20 21:55:44 -05:00
parent 6d97aba32d
commit 794a1a5452
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
2 changed files with 13 additions and 7 deletions

View File

@ -19,8 +19,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) { func applicationDidFinishLaunching(_ aNotification: Notification) {
connect() connect()
UserDefaults.standard.addObserver(self, forKeyPath: "mpdHost", options: .new, context: nil) preferences.addObserver(self, forKeyPath: "mpdHost")
UserDefaults.standard.addObserver(self, forKeyPath: "mpdPort", options: .new, context: nil) preferences.addObserver(self, forKeyPath: "mpdPort")
} }
func applicationWillTerminate(_ aNotification: Notification) { func applicationWillTerminate(_ aNotification: Notification) {

View File

@ -9,24 +9,26 @@
import Foundation import Foundation
struct Preferences { struct Preferences {
let preferences = UserDefaults.standard
var mpdHost: String? { var mpdHost: String? {
get { get {
return UserDefaults.standard.string(forKey: "mpdHost") return preferences.string(forKey: "mpdHost")
} }
set { set {
UserDefaults.standard.set(newValue, forKey: "mpdHost") preferences.set(newValue, forKey: "mpdHost")
} }
} }
var mpdPort: Int? { var mpdPort: Int? {
get { get {
return UserDefaults.standard.value(forKey: "mpdPort") as? Int return preferences.value(forKey: "mpdPort") as? Int
} }
set { set {
if (newValue.map { $0 > 0 } ?? false) { if (newValue.map { $0 > 0 } ?? false) {
UserDefaults.standard.set(newValue, forKey: "mpdPort") preferences.set(newValue, forKey: "mpdPort")
} else { } else {
UserDefaults.standard.removeObject(forKey: "mpdPort") preferences.removeObject(forKey: "mpdPort")
} }
} }
} }
@ -38,4 +40,8 @@ struct Preferences {
var mpdPortOrDefault: Int { var mpdPortOrDefault: Int {
return mpdPort ?? 6600 return mpdPort ?? 6600
} }
func addObserver(_ observer: NSObject, forKeyPath keyPath: String) {
preferences.addObserver(observer, forKeyPath: keyPath, options: .new, context: nil)
}
} }