Understanding and Implementing Key-Value Observing (KVO) in iOS
This article explains what Key-Value Observing (KVO) is, how to use it in iOS development, and the runtime mechanisms—such as isa‑swizzling and dynamic subclass creation—that enable automatic property change notifications, while also showing how to build a custom KVO system.
Key‑Value Observing (KVO) is a mechanism that lets objects be notified when specified properties of other objects change, making it easy to monitor state changes of UI controls, strings, and other values.
The official Apple definition is: "Key‑value observing is a mechanism that allows objects to be notified of changes to specified properties of other objects."
KVO works automatically for any NSObject subclass that defines properties in the usual way. To use KVO you register an observer with addObserver:forKeyPath:options:context: , implement observeValueForKeyPath:ofObject:change:context: in the observer, and later remove the observer with removeObserver:forKeyPath: .
The underlying implementation relies on a technique called isa‑swizzling . When an observer is added, the runtime creates an intermediate subclass (e.g., NSKVONotifying_FeClass ) and changes the observed object's isa pointer to point to this subclass. The subclass overrides the setter of the observed property, calling willChangeValueForKey: before the change and didChangeValueForKey: after, which triggers the notification.
Debugging shows the original object's isa pointing to its real class (e.g., FeClass ) and, after registration, pointing to the generated NSKVONotifying_FeClass . The overridden setter records the old value, updates the property, and then notifies the observer.
To build a custom KVO system, you can add a category to NSObject , dynamically create a subclass with objc_registerClassPair() , add a custom setter using class_addMethod() , and associate the observer via objc_setAssociatedObject() . Inside the custom setter you call the original superclass setter with objc_msgSendSuper() , then retrieve the observer and invoke its observeValueForKeyPath:ofObject:change:context: method.
Overall, KVO is an application of the Observer design pattern in Cocoa, providing a powerful way to react to property changes in iOS apps.
Reference: "[深入浅出Cocoa]详解键值观察(KVO)及其实现机理"
JD Retail Technology
Official platform of JD Retail Technology, delivering insightful R&D news and a deep look into the lives and work of technologists.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.