Last active
November 9, 2015 21:24
-
-
Save njdehoog/7cbc7300dba4cbd490e9 to your computer and use it in GitHub Desktop.
KVO in Swift
This file contains 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
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) | |
} | |
} | |
} |
This file contains 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
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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice1, thanks.