Key-value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects. You can use key-value observing with a Swift class, as long as the class inherits from the NSObject class. You can use these two steps to implement key-value observing in Swift.
- Add the dynamic modifier and @objc attribute to any property you want to observe. For more information on dynamic, see Requiring Dynamic Dispatch.
class MyObjectToObserve: NSObject {
@objc dynamic var myDate = NSDate()
func updateDate() {
myDate = NSDate()
}
}
- Create an observer for the key path and call the observe(_:options:changeHandler) method like description on Apple doc. Or create a observer on observable(
MyObjectToObserve
) directly
var myContext = 0
class MyObserver: NSObject {
@objc var objectToObserve: MyObjectToObserve
var observation: NSKeyValueObservation?
init(object: MyObjectToObserve) {
objectToObserve = object
super.init()
objectToObserve.addObserver(self, forKeyPath: "myDate", options: .new, context: &myContext)
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "myDate")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//print("here , \(keyPath), \(object), \(change?[NSKeyValueChangeKey.newKey])")
guard context == &myContext else { return }
if let value = change?[NSKeyValueChangeKey.newKey] {
print("Observation, myDate changed: \(value)")
}
}
}
- Verifiy observer:
let observed = MyObjectToObserve()
let observer = MyObserver(object: observed)
observed.updateDate()
sleep(3)
observed.updateDate()
print("finished")
You will see output in Xcode debug area:
Observation: myDate changed: 2018-01-30 18:15:41 +0000
Observation: myDate changed: 2018-01-30 18:15:44 +0000
finished
awesome
LikeLike