Notify objects about changes to the properties of other objects.
- Swift Standard Library
Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from
Annotate a Property for Key-Value Observing
Mark properties that you want to observe through key-value observing with both the
@objc attribute and the
dynamic modifier. The example below defines the
My class with a property—
my—that can be observed:
Define an Observer
An instance of an observer class manages information about changes made to one or more properties. When you create an observer, you start observation by calling the
observe(_: method with a key path that refers to the property you want to observe.
In the example below, the
\.object key path refers to the
my property of
You use the
new properties of the
NSKey instance to see what's changed about the property you're observing.
If you don't need to know how a property has changed, omit the
options parameter. Omitting the
options parameter forgoes storing the new and old property values, which causes the
new properties to be
Associate the Observer with the Property to Observe
You associate the property you want to observe with its observer by passing the object to the initializer of the observer:
Respond to a Property Change
Objects that are set up to use key-value observing—such as
observed above—notify their observers about property changes. The example below changes the
my property by calling the
update method. That method call automatically triggers the observer's change handler:
The example above responds to the property change by printing both the new and old values of the date.