- Mastering macOS Programming
- Stuart Grimshaw
- 143字
- 2021-07-02 22:54:43
Reacting to value changes
We now need to add a handler method to the class, which will be called whenever an observed property changes. Add the following method to the PeopleWatcher class:
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?)
{
if context == &myContext {
if let keyPath = keyPath
{
print("\(keyPath) has changed to",
"\(change![NSKeyValueChangeKey.newKey]!)")
}
}
}
We override NSObject's observeValue(keyPath: object: change: context:) method. This is a terribly named function, since we are observing already; the method is about handling property changes.
If the context pointer passed is the one created by this instance of the class (remember, they're all 0, but are different instances of 0, and it is the memory address of that instance that we are checking), we react to the notification.
For the moment, we'll just log the change.