Search code examples
cocoakey-value-observingfoundationinternals

How is Key-Value Observing implemented internally?


I got answer about Foundation magic for this question: What's the most *simple* way to implement a plain data object which conforms key-value-observing?

What's the magic? How it work internally? Because it's dangerous using framework which I can't understand its internal behavior, I want to know its behavior. Currently, I cannot understand how it work without any method definitions.


Solution

  • Apple's documentation describes how KVO is implemented internally.

    The gist of it is that when you register an observer on an object, the framework dynamically creates a subclass of the object's original class, and adjusts the object to appear as an instance of this new dynamic class. You can see this if you inspect an object in the debugger after it has had an observer registered.

    This new class intercepts messages to the object and inspects them for those matching certain patterns (such as the getters, setters, and collection access).