Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
eonil Avatar asked Mar 22 '11 04:03

eonil


2 Answers

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).

like image 158
一二三 Avatar answered Nov 08 '22 17:11

一二三


In a nutshell: Objective-C 2.0's @property declaration creates accessor methods for the named property, so there are method definitions. @property is just a shorthand way to define them which avoids a lot of repetitious boilerplate code.

When you observe a property, a private subclass is created which implements accessors that call the appropriate notification methods before and after changing the property value. A technique known as "isa swizzling" is then used to change the class of the observed object.

like image 26
Sherm Pendley Avatar answered Nov 08 '22 18:11

Sherm Pendley