Skip to content

Instantly share code, notes, and snippets.

@cybercase
Last active August 6, 2017 12:39
Show Gist options
  • Save cybercase/c8963f04984f801cecf82ffea28286e1 to your computer and use it in GitHub Desktop.
Save cybercase/c8963f04984f801cecf82ffea28286e1 to your computer and use it in GitHub Desktop.
While waiting for swift4 observe method
//
// 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