KVO (Key Value Observing) in Swift
Key-value observing is a mechanism that enables an object to be notified directly when a property of another object changes.
It is a mode of communication between objects in applications designed in conformance with the Model-View-Controller design pattern.
Controller can Observe Model and View can Observe Controller and Model. So, change in model object property can be handled gracefully using KVO.
Key-Value Observing requires your Object to conform to NSKeyValueObserving protocol. Any Class which inherits NSObject automatically implements NSKeyValueObserving protocol as NSObject conforms to NSKeyValueObserving.
Note: NSKeyValueObserving APIs are not the cleanest to use(in terms of syntax and arguments). But having said that it’s powerful and developer should use it.
NSKeyValueObserving: An informal protocol that objects adopt to be notified of changes to the specified properties of other objects.
How to register and observe another object property?
Registering for Observation:
Observation
Registers the observer object to receive KVO notifications for the key path relative to the object receiving this message.
func addObserver(_ observer: NSObject,
forKeyPath keyPath: String,
options: NSKeyValueObservingOptions = [],
context: UnsafeMutableRawPointer?)
Registers the observer object to receive KVO notifications for the key path relative to the object receiving this message.
Observe Notification method:
func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?)
Removing an Observer:
Another major issue when working with Key-Value Observing is memory management. Observers need to be explicitly removed when they are no longer interested in receiving notifications for a particular key path. You have two options.
deinit {
removeObserver(self, forKeyPath: #keyPath(property))
}
It’s very simple to understand and use, still developers don’t use it frequently.
Hope you understood this pattern and will use it in your project as well.