Key Value Observing (KVO) with Swift Closures
This is an Swift class to allow KVO observing using Swift closures, useable from a Swift class that does not subclass NSObject
.
From Swift, create a KeyValueObserver
instance with the object being observed, the key path to observe and a closure to be called. As long as this instance remains alive, observations will be reported to the closure. To remove the observer, release the KeyValueObserver
instance (so assign it to an optional so you can assign that to nil
to release it).
let button = UIButton() var kvo: KeyValueObserver? = KeyValueObserver(source: button, keyPath: "selected", options: .New) { (kvo, change) in NSLog("observing %@ %@", kvo.keyPath, change) } button.selected = true button.selected = false kvo = nil button.selected = true
You can save the observer in an...