Skip to content

Instantly share code, notes, and snippets.

@njdehoog
Last active November 9, 2015 21:24
Show Gist options
  • Save njdehoog/7cbc7300dba4cbd490e9 to your computer and use it in GitHub Desktop.
Save njdehoog/7cbc7300dba4cbd490e9 to your computer and use it in GitHub Desktop.
KVO in Swift
class KeyValueObserver: NSObject {
typealias KeyValueObservingCallback = (change: [NSObject : AnyObject]) -> Void
private let object: NSObject
private let keyPath: String
private let callback: KeyValueObservingCallback
private var kvoContext = 0
init(object: NSObject, keyPath: String, options: NSKeyValueObservingOptions, callback: KeyValueObservingCallback) {
self.object = object
self.keyPath = keyPath
self.callback = callback
super.init()
object.addObserver(self, forKeyPath: keyPath, options: options, context: &kvoContext)
}
deinit {
object.removeObserver(self, forKeyPath: keyPath, context: &kvoContext)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &kvoContext {
self.callback(change: change)
}
else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
}
class Foo {
private var observer: KeyValueObserver?
private let bar = Bar()
init() {
self.observer = KeyValueObserver(object: bar, keyPath: "string", options: .New) {
[unowned self] change in
println("bar changed: \(self.bar.string)")
}
bar.string = "world"
}
deinit {
self.observer = nil
}
}
class Bar: NSObject {
dynamic var string = "hello"
}
Copy link

ghost commented Sep 3, 2015

nice1, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment