Skip to content

Instantly share code, notes, and snippets.

@dgazzoni
Created February 6, 2019 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgazzoni/b3067cf0407ac0cd78946f0260af14fe to your computer and use it in GitHub Desktop.
Save dgazzoni/b3067cf0407ac0cd78946f0260af14fe to your computer and use it in GitHub Desktop.
// Code (in app delegate)
func setupObservers() {
observations.append(
UserDefaults.standard.observe(
\UserDefaults.selectedPreset,
options: [.initial, .new],
changeHandler: selectedPresetChanged
)
)
UserDefaults.standard.addObserver(self, forKeyPath: #keyPath(UserDefaults.selectedPreset), options: [.initial, .new], context: nil)
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
NSLog("""
observeValue(
forKeyPath: \(String(describing:keyPath)),
of: \(String(describing:object)),
change: \(String(describing:change)),
context: \(String(describing:context))
)
""")
}
func selectedPresetChanged(
_: UserDefaults,
object: NSKeyValueObservedChange<ControlModeWithPresets>
) {
NSLog(
"selectedPresetChanged() " +
"newValue = \(String(describing: object.newValue))"
)
}
// Output:
// 2019-02-05 22:20:17.883391-0200 BattChgCtrl[8152:282384] selectedPresetChanged() newValue = nil
// 2019-02-05 22:20:17.883846-0200 BattChgCtrl[8152:282384] observeValue(
// forKeyPath: Optional("selectedPreset"),
// of: Optional(<NSUserDefaults: 0x600000c409f0>),
// change: Optional([__C.NSKeyValueChangeKey(_rawValue: kind): 1, __C.NSKeyValueChangeKey(_rawValue: new): {
// mode = Automatic;
// presetId = "F88B1590-2ABA-4AFF-81B5-BA1A128ACD48";
// }]),
// context: nil
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment