In a 09 article, the internal implementation of KVO was elaborated in more depth. KVO is the basis for implementing the cocoa bindings, which provides a way for the corresponding objects to be notified when a property changes. In other languages, this observer pattern usually needs to be implemented separately, whereas in objective-c it is usually not necessary to add additional code.OverviewHow is this going to be achieved? In fact, this is achieved through OBJECTIVE-C's powerful runtime. When you first observe an object, runtime creates a new subclass that inherits the original class. In this new class, it overrides all the observed keys and then points the object's Isa pointer to the newly created class, which tells the objective-c what type of object the object is at runtime. So object magically becomes an instance of the new subclass. These overridden methods implement how to notify observers. When a key is changed, the Setkey method is triggered, but the method is rewritten and the send notification mechanism is added internally. (Of course, you can not take the Setxxx method, such as directly modify the Ivar, but it is not recommended). Interestingly, Apple does not want this mechanism to be exposed to the external part. In addition to setters, this dynamically generated subclass also overrides the-class method, returning to the original class! If you do not look closely, the object that has been kvo seems to be no different from the original object.Deep DiveLet's look at how these are implemented. I wrote a program to demonstrate the mechanism behind the KVO.
- Gcc-o kvoexplorer-framework Foundation KVOEXPLORER.M
- #import <Foundation/Foundation.h>
- #import <objc/runtime.h>
- @Interface Testclass:nsobject
- {
- int x;
- int y;
- int z;
- }
- @property int x;
- @property int y;
- @property int z;
- @end
- @implementation TestClass
- @synthesize x, y, Z;
- @end
- Static Nsarray *classmethodnames (Class c)
- {
- Nsmutablearray *array = [Nsmutablearray array];
- unsigned int methodcount = 0;
- Method *methodlist = Class_copymethodlist (c, &methodcount);
- unsigned int i;
- For (i = 0; i < Methodcount; i++)
- [Array Addobject:nsstringfromselector (Method_getname (methodlist[i))];
- Free (methodlist);
- return array;
- }
- static void Printdescription (nsstring *name, id obj)
- {
- NSString *str = [NSString stringWithFormat:
- @"%@:%@\n\tnsobject class%S\N\TLIBOBJC class%s\n\timplements methods <%@>",
- Name
- Obj
- Class_getname ([obj class]),
- Class_getname (Obj->isa),
- [Classmethodnames (Obj->isa) componentsjoinedbystring:@","]];
- printf ("%s\n", [str utf8string]);
- }
- int main (int argc, char **argv)
- {
- [NSAutoreleasePool new];
- TestClass *x = [[TestClass alloc] init];
- TestClass *y = [[TestClass alloc] init];
- TestClass *xy = [[TestClass alloc] init];
- TestClass *control = [[TestClass alloc] init];
- [x addobserver:x forkeypath:@"x" options:0 context:null];
- [XY addobserver:xy forkeypath:@"x" options:0 context:null];
- [y addobserver:y forkeypath:@"y" options:0 context:null];
- [XY addobserver:xy forkeypath:@"y" options:0 context:null];
- Printdescription (@"control", control);
- Printdescription (@"x", x);
- Printdescription (@"y", y);
- Printdescription (@"xy", XY);
- printf ("Using nsobject methods, normal Setx:is%p, overridden Setx:is%p\n",
- [Control Methodforselector: @selector (SetX:)],
- [x methodforselector: @selector (SetX:)]);
- printf ("Using LIBOBJC functions, normal setx:is%p, overridden Setx:is%p\n",
- Method_getimplementation (Class_getinstancemethod (Object_getclass (Control),
- @selector (SetX:))),
- Method_getimplementation (Class_getinstancemethod (Object_getclass (x),
- @selector (SetX:))));
- return 0;
- }
We look at it from beginning to end. First, a TestClass class is defined, which has 3 properties. Then we define some convenient methods for debugging. Classmethodnames uses the Objective-c run-time method to traverse a class to get a list of methods. Note that these methods do not include methods for the parent class. Printdescription prints all the information about the object, including the class information (including the-class and the class obtained by the runtime), and the method implemented by this class. Then 4 TestClass instances were created, each using a different way of observing. x instances have one observer observing Xkey,y, and XY is similar. To make comparisons, zkey have no observers. The last control instance does not have any observers. Then print out the objects of the 4 x-Description. You then continue to print the overridden setter memory address and the memory address of the setter that was not overridden for comparison. This was done two times because-methodforselector: there was no way to rewrite it. Kvo tried to conceal the fact that it actually created a new subclass! But using the run-time method is true.Run codeLook at the output of this piece of code
- Control: <TestClass:0x104b20>
- NSObject class TestClass
- LIBOBJC class TestClass
- Implements methods <setx:, X, sety:, Y, Setz:, z>
- X: <TestClass:0x103280>
- NSObject class TestClass
- LIBOBJC class Nskvonotifying_testclass
- Implements methods <sety:, SetX:, class, Dealloc, _iskvoa>
- Y: <TestClass:0x104b00>
- NSObject class TestClass
- LIBOBJC class Nskvonotifying_testclass
- Implements methods <sety:, SetX:, class, Dealloc, _iskvoa>
- XY: <TestClass:0x104b10>
- NSObject class TestClass
- LIBOBJC class Nskvonotifying_testclass
- Implements methods <sety:, SetX:, class, Dealloc, _iskvoa>
- Using nsobject methods, normal Setx:is 0x195e, overridden Setx:is 0x195e
- Using LIBOBJC functions, normal setx:is 0x195e, overridden Setx:is 0x96a1a550
First, it outputs the controlobject, without any problems, its class is TestClass, and implements 6 Set/get methods. Then there are 3 observed objects. Note that-class still shows TestClass, using Object_getclass to show the true face of this object: It is an instance of Nskvonotifying_testclass. This nskvonotifying_testclass is a dynamically generated subclass!. Notice how it achieves these two observed setters. You will find that it is very clever and does not rewrite-setz: Although it is also a setter, because it is not observed. Also note that 3 instances correspond to the same class, which means that two setters are rewritten, although two of them only observe one attribute. This can be a bit of an efficiency problem, because even if the property that is not observed is going to be rewritten by the setter, Apple obviously feels that it is better than separating the dynamic subclass, which I think is the right choice. You will see 3 other methods. There are rewritten-class methods that have been mentioned before, pretending to be the original class. There are also-dealloc methods to deal with some finishing touches. There is also a _iskvoa method that looks like a private method. Next, we output-SETX: the implementation. Use-methodforselector: Returns the same value. Because-SETX: Already overridden in subclasses, this means that methodforselector: using-class in the internal implementation, the result is incorrect. Finally, we get different output results through the runtime. As an excellent explorer, let's go into the debugger to see how this second approach is implemented:
- (gdb) print (IMP) 0x96a1a550
- $ = (IMP) 0x96a1a550 <_NSSetIntValueAndNotify>
Appears to be an internal method that uses Nm-a for the foundation to get a complete list of private methods:
- 0013df80 T __nssetboolvalueandnotify
- 000a0480 T __nssetcharvalueandnotify
- 0013e120 T __nssetdoublevalueandnotify
- 0013e1f0 T __nssetfloatvalueandnotify
- 000e3550 T __nssetintvalueandnotify
- 0013e390 T __nssetlonglongvalueandnotify
- 0013E2C0 T __nssetlongvalueandnotify
- 00089df0 T __nssetobjectvalueandnotify
- 0013E6F0 T __nssetpointvalueandnotify
- 0013e7d0 T __nssetrangevalueandnotify
- 0013e8b0 T __nssetrectvalueandnotify
- 0013e550 T __nssetshortvalueandnotify
- 0008ab20 T __nssetsizevalueandnotify
- 0013e050 T __nssetunsignedcharvalueandnotify
- 0009fcd0 T __nssetunsignedintvalueandnotify
- 0013e470 T __nssetunsignedlonglongvalueandnotify
- 0009FC00 T __nssetunsignedlongvalueandnotify
- 0013e620 T __nssetunsignedshortvalueandnotify
This list can also find something interesting. For example, Apple writes a corresponding implementation for each primitive type. Objective-c object will be used in fact only __nssetobjectvalueandnotify, but need a set to correspond to the rest, and does not seem to achieve complete, such as long dobule or _bool are not. There is not even a method for a generic pointer type (generic pointer type). Therefore, the properties that are not in the list of methods are actually not supported for KVO. KVO is a powerful tool, sometimes too powerful, especially with an automatic triggering notification mechanism. Now you know how it's implemented internally, and that knowledge may help you better use it, or make it easier to debug when it goes wrong. If you're going to use KVO, maybe you can take a look at one of my other articles Key-value observing done right Source: no net Left blog http://www.cocoachina.com/industry/20140107/7667.html
Translation Internal implementation of KVO