Last active
August 6, 2017 12:39
-
-
Save cybercase/c8963f04984f801cecf82ffea28286e1 to your computer and use it in GitHub Desktop.
While waiting for swift4 observe method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Prop.swift | |
// GQLC | |
// | |
// Created by Stefano Brilli on 01/08/2017. | |
// Copyright © 2017 Stefano Brilli. All rights reserved. | |
// | |
import Cocoa | |
class Prop<T>: NSObject { | |
var target: NSObject | |
var keyPath: String | |
var callback: (T?, T?) -> Void | |
init(target: NSObject, keyPath: String, callback: @escaping (T?, T?) -> Void) { | |
self.target = target | |
self.keyPath = keyPath | |
self.callback = callback | |
super.init() | |
target.addObserver(self, forKeyPath: keyPath, options: [.initial, .new, .old], context: nil) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
let new = change?[.newKey] as? T | |
let old = change?[.oldKey] as? T | |
self.callback(new, old) | |
} | |
deinit { | |
target.removeObserver(self, forKeyPath: keyPath) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment