4.11 · Key-value coding and observing
Two old Cocoa mechanisms still sit under Core Data, bindings, animation and many SDKs. Both are built on the runtime tables, so they work only for what the runtime can see.
Mental model. KVC is looking a property up by name. KVO is subscribing to a property’s setter through a hidden subclass.
Coding and observing
String keys, key paths, the generated subclass, and derived properties.
- What is key-value coding, what can it do that normal property access cannot, and how does it fail?
KVC reads and writes properties by string name: value(forKey: "age"), setValue(31, forKey: "age"), and a dotted key path such as "address.city" that walks… - What does KVO do to an observed object at run time, and how can you see it?
When you observe an object, the runtime creates (once per class) a subclass named NSKVONotifying_Model and switches the instance’s isa to it with… - How do you make a computed property observable in KVO, and when do notifications fire?
A computed property has no setter to intercept, so KVO cannot know when it changes. You declare the dependency instead: override class func…
More in Objective-C & interop
- 4.1 · Message send, selectors, forwarding, isa
- 4.2 · Categories, associated objects, load and initialize
- 4.3 · NSObject, class clusters, copying
- 4.4 · @objc, what does not bridge, and error bridging
- 4.5 · Nullability, lightweight generics, Swift-friendly names
- 4.6 · Method swizzling, and when it is a footgun
- 4.7 · Reading Objective-C, blocks, and manual reference counting
- 4.8 · Mixed-language projects, costs, and migrating a large app
- 4.9 · How Objective-C declarations arrive in Swift
- 4.10 · The runtime up close: introspection, encodings, IMPs and exceptions
- 4.12 · What crosses the boundary: inference and concurrency