Underlying implementation principle of KVO and underlying principle of kvo

Source: Internet
Author: User

Underlying implementation principle of KVO and underlying principle of kvo

KVO is the basis for implementing Cocoa Bindings. It provides a method to notify the corresponding objects when a property changes. In other languages, this observer mode usually needs to be implemented independently, while in Objective-C, it can be used without additional code,

How is this implemented? It is actually implemented through the powerful runtime of OC. When you observe an object for the first time, runtime creates a new subclass that inherits the original class. In this new class, it overwrites all the observed keys, next, point the isa pointer of OC to the newly created class (this pointer tells oc which type of object is an object at runtime ). So the object becomes a new subclass instance;

These override methods implement how to notify the observer. When a key is changed, the setkey method is triggered, but this method is overwritten, And the sending notification mechanism is added internally. (Of course, I can also leave the set method, for example, directly modifying ivar, but this is not recommended ).

Interestingly, Apple does not want this mechanism to be exposed externally. In addition to setters, this dynamically generated subclass also overwrites the-class method and returns the original class! If you do not take a closer look, the objects that have been passed by KVO will look like the original objects.


The following is a program that demonstrates the mechanism hidden behind KVO.

  1. // Gcc-o kvoexplorer-framework Foundation kvoexplorer. m
  2. # Import <Foundation/Foundation. h>
  3. # Import <objc/runtime. h>
  4.  
  5.  
  6. @InterfaceTestClass: NSObject
  7. {
  8. IntX;
  9. IntY;
  10. IntZ;
  11. }
  12. @ PropertyIntX;
  13. @ PropertyIntY;
  14. @ PropertyIntZ;
  15. @ End
  16.  
  17. @ Implementation TestClass
  18. @ Synthesize x, y, z;
  19. @ End
  20.  
  21. StaticNSArray * ClassMethodNames (Class c)
  22. {
  23. NSMutableArray * array = [NSMutableArray array];
  24. UnsignedIntMethodCount = 0;
  25. Method * methodList = class_copyMethodList (c, & methodCount );
  26. UnsignedIntI;
  27. For(I = 0; I <methodCount; I ++)
  28. [Array addObject: NSStringFromSelector (method_getName (methodList [I])];
  29. Free (methodList );
  30. ReturnArray;
  31. }
  32.  
  33. Static VoidPrintDescription (NSString * name, id obj)
  34. {
  35. NSString * str = [NSString stringWithFormat:
  36. @ "% @: % @ \ N \ tNSObject class % s \ n \ tlibobjc class % s \ n \ timplements methods <% @> ",
  37. Name,
  38. Obj,
  39. Class_getName ([objClass]),
  40. Class_getName (obj-> isa ),
  41. [ClassMethodNames (obj-> isa) componentsJoinedByString: @ ","];
  42. Printf ("% s \ n", [str UTF8String]);
  43. }
  44.  
  45. IntMain (IntArgc,Char** Argv)
  46. {
  47. [NSAID utoreleasepoolNew];
  48. TestClass * x = [[TestClass alloc] init];
  49. TestClass * y = [[TestClass alloc] init];
  50. TestClass * xy = [[TestClass alloc] init];
  51. TestClass * control = [[TestClass alloc] init];
  52. [X addObserver: x forKeyPath: @ "x" options: 0 context: NULL];
  53. [Xy addObserver: xy forKeyPath: @ "x" options: 0 context: NULL];
  54. [Y addObserver: y forKeyPath: @ "y" options: 0 context: NULL];
  55. [Xy addObserver: xy forKeyPath: @ "y" options: 0 context: NULL];
  56. PrintDescription (@ "control", control );
  57. PrintDescription (@ "x", x );
  58. PrintDescription (@ "y", y );
  59. PrintDescription (@ "xy", xy );
  60. Printf ("Using NSObject methods, normal setX: is % p, overridden setX: is % p \ n ",
  61. [Control methodForSelector: @ selector (setX :)],
  62. [X methodForSelector: @ selector (setX :)]);
  63. Printf ("Using libobjc functions, normal setX: is % p, overridden setX: is % p \ n ",
  64. Method_getImplementation (class_getInstanceMethod (object_getClass (control ),
  65. @ Selector (setX :))),
  66. Method_getImplementation (class_getInstanceMethod (object_getClass (x ),
  67. @ Selector (setX :))));
  68. Return0;
  69. }
Let's take a closer look from start to end. First, a class of TestClass is defined. It has three attributes. Then some convenient debugging methods are defined. ClassMethodNames uses the Objective-C Runtime method to traverse a class and obtain the method list. Note that these methods do not include the methods of the parent class. PrintDescription prints all the information about the object, including the class information (including-class and the class obtained through the operation), and the implementation method of this class. Then four TestClass instances are created, each of which uses different observation methods. An observer of x instance observes xkey, y, and xy. For comparison, zkey has no observer. The last control instance does not have any observer. Then, four objects descriptions are printed. Then print the rewritten setter memory address and the memory address of the unoverwritten setter for comparison. This is done twice because-methodForSelector: The method cannot be rewritten. KVO tries to conceal the fact that it actually created a new subclass! However, the running method is invisible. Run codeLet's look at the output of this Code.
 
  1. Control: <TestClass: 0x0000b20>
  2. NSObjectClassTestClass
  3. LibobjcClassTestClass
  4. ImplementsMethods <setX:, x, setY:, y, setZ:, z>
  5. X: <TestClass: 0 x103280>
  6. NSObjectClassTestClass
  7. LibobjcClassNSKVONotifying_TestClass
  8. ImplementsMethods <setY:, setX :,Class, Dealloc, _ isKVOA>
  9. Y: <TestClass: 0x0000b00>
  10. NSObjectClassTestClass
  11. LibobjcClassNSKVONotifying_TestClass
  12. ImplementsMethods <setY:, setX :,Class, Dealloc, _ isKVOA>
  13. Xy: <TestClass: 0x0000b10>
  14. NSObjectClassTestClass
  15. LibobjcClassNSKVONotifying_TestClass
  16. ImplementsMethods <setY:, setX :,Class, Dealloc, _ isKVOA>
  17. Using NSObject methods, normal setX: is 0x195e, overridden setX: is 0x195e
  18. Using libobjc functions, normal setX: is 0x195e, overridden setX: is 0x96a1a550
First, it outputs controlobject. There is no problem. Its class is TestClass and six set/get methods are implemented. Then there are three observed objects. Note: The class still displays TestClass, and object_getClass is used to show the true face of this object: it is an instance of NSKVONotifying_TestClass. This NSKVONotifying_TestClass is a dynamically generated subclass! Note how it implements the two observed setters. You will find that it is very clever and has not been rewritten-setZ:, although it is also a setter, because it is not observed. At the same time, it is noted that the three instances correspond to the same class, that is, both setters are overwritten, even though two instances only observe one attribute. This will bring about a little efficiency problem, because even if the property is not observed, it will go through the rewritten setter, but apple obviously thinks this score is better to generate a dynamic subclass, I also think this is a correct choice. You will see three other methods. There is a previously mentioned-class method that has been rewritten. Pretend that you are still the original class. There is also the-dealloc method to deal with some final work. There is also a _ isKVOA method, which looks like a private method. Next, we will output the implementation of-setX. Use-methodForSelector: returns the same value. Because-setX: has been rewritten in the subclass, this means that methodForSelector: Uses-class in the internal implementation and gets the wrong result. Finally, we get different output results through the runtime. As an excellent explorer, let's go to debugger to see how the second method is implemented:
 
  1. (Gdb) print (IMP) 0x96a1a550
  2. $1 = (IMP) 0x96a1a550 <_ NSSetIntValueAndNotify>
It looks like an internal method. Use nm-a for Foundation to get a complete list of private methods:
 
  1. 0013df80 t _ NSSetBoolValueAndNotify
  2. 000a00000t _ NSSetCharValueAndNotify
  3. 0013e120 t _ NSSetDoubleValueAndNotify
  4. 0013e1f0 t _ NSSetFloatValueAndNotify
  5. 000e3550 t _ NSSetIntValueAndNotify
  6. 0013e390 t _ NSSetLongLongValueAndNotify
  7. 0013e2c0 t _ NSSetLongValueAndNotify
  8. 00089df0 t _ NSSetObjectValueAndNotify
  9. 0013e6f0 t _ NSSetPointValueAndNotify
  10. 0013e7d0 t _ NSSetRangeValueAndNotify
  11. 0013e8b0 t _ NSSetRectValueAndNotify
  12. 0013e550 t _ nsset1_valueand1_y
  13. 0008ab20 t _ NSSetSizeValueAndNotify
  14. 0013e050 t _ NSSetUnsignedCharValueAndNotify
  15. 0009fcd0 t _ NSSetUnsignedIntValueAndNotify
  16. 0013e470 t _ NSSetUnsignedLongLongValueAndNotify
  17. 0009fc00 t _ NSSetUnsignedLongValueAndNotify
  18. 0013e620 t _ nssetunsigned1_valueandnotify
This list also finds some interesting things. For example, Apple writes the corresponding implementation for each primitive type. Objective-C objects only use _ NSSetObjectValueAndNotify, but a complete set is required to correspond to the rest, and it does not seem completely implemented, such as long dobule or _ Bool. The method is not even provided for the general pointer type (generic pointer type. Therefore, attributes not in this method list do not actually support KVO. KVO is a powerful tool, sometimes too powerful, especially with the automatic notification trigger mechanism. Now you know how it is implemented internally. This knowledge may help you better use it, or facilitate debugging when it fails.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.