Skip to content

Instantly share code, notes, and snippets.

@preble
Created January 7, 2016 18:59
Show Gist options
  • Save preble/249ab3aade4a70be76e6 to your computer and use it in GitHub Desktop.
Save preble/249ab3aade4a70be76e6 to your computer and use it in GitHub Desktop.
Swift-like KVO
import Foundation
/// Helper object for more Swift-like KVO. To create, call NSObject.addObserverForKeyPath(_:handler:).
class KeyValueObserver: NSObject {
private weak var observing: NSObject?
private var keyPath: String
private var handler: () -> Void
private init(observing: NSObject, keyPath: String, handler: () -> Void) {
self.observing = observing
self.keyPath = keyPath
self.handler = handler
super.init()
observing.addObserver(self, forKeyPath: keyPath, options: [], context: nil)
}
deinit {
remove()
}
/// Manually stop observing.
func remove() {
observing?.removeObserver(self, forKeyPath: keyPath)
observing = nil
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
assert(keyPath == self.keyPath)
handler()
}
}
extension NSObject {
/// Observe keyPath on the receiver for the lifetime of the returned KeyValueObserver object, or until remove() is called upon it.
func addObserverForKeyPath(keyPath: String, handler: () -> Void) -> KeyValueObserver {
let observer = KeyValueObserver(observing: self, keyPath: keyPath, handler: handler)
return observer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment