The underlying implementation principle of IOS KVC & KVO

Source: Internet
Author: User

KVO Internal Implementation principle

1. KVO is implemented based on the runtime mechanism.

2. When an object of a class is observed for the first time, a derived class of the class is created dynamically at runtime, overriding the setter method of any observed attribute in the base class in this derived class;

Derived classes implement a true notification mechanism in overridden setter methods (person---Nskvonotifying_person)

1, KVC, refers to nskeyvaluecoding, an informal protocol, provides a mechanism to indirectly access the properties of the object. Instead of being accessed by invoking a setter, getter method. KVO is one of the key technologies based on KVC implementation.

Demo:

@interface Myperson:nsobject

{

Nsstring*_name;

int _age;

int _height;

int _weight;

} @end

@interface Testviewcontroller:uiviewcontroller

@property (nonatomic, retain) Myperson*testperson;

@end

-(void) TESTKVC

{

Testperson = [[MyPerson alloc] init];

NSLog (@ "Testperson ' init height =%@", [Testperson valueforkey:@ "height"]);

[Testperson setvalue:[nsnumber numberwithint:168]forkey:@ "height"]; NSLog (@ "Testperson ' s height =%@", [Testperson valueforkey:@ "height"]);

}

The first code defines a MyPerson class that has a _height property, but does not provide any getter/setter access methods. At the same time, there is a MyPerson object pointer in the Testviewcontroller class.

When MyPerson is instantiated, it is generally impossible to access the object's _height property, but by KVC we do, the code is TESTKVC this function.

After running, the print value is:

2015-3-13 11:16:21.970 test[408:c07] Testperson ' s init height = 0

2015-3-13 11:16:21.971 test[408:c07] Testperson ' s height = 168

This means that the _height property is actually read and written.

Common methods of KVC:

-(ID) Valueforkey: (NSString *) key; -(void) SetValue: (ID) value Forkey: (NSString *) key;

The Valueforkey method reads the properties of the object according to the value of the key, Setvalue:forkey: The property of the object is written according to the value of the key.

Attention:

(1). The value of key must be correct and if misspelled, an exception will occur

(2). When the value of key is undefined, Valueforundefinedkey: This method will be called, and if you write this method yourself, the value of key will be called in error.

(3). Because the class key is nested repeatedly, so there is a keypath concept, KeyPath is to use the. Number to link a key so that it can be accessed according to this path

(4). Nsarray/nsset, etc. all support KVC

2, KVO is the abbreviation of KeyValue observe, Chinese is the key value observation. This is a typical observer pattern, and the observer will be notified when the key value changes. iOS has a notification mechanism that can also be notified, but this mechanism needs to have a center, in contrast KVO more concise and direct.


The use of KVO is also very simple, is simple 3 steps.
1. Register the properties of the object to be observed AddObserver:forKeyPath:options:context:
2. Implement ObserveValueForKeyPath:ofObject:change:context: Method, this method is automatically called when the observed property changes
3. Unregister observation RemoveObserver:forKeyPath:context:

Demo:

  1. @interface Myperson:nsobject
  2. {
  3. NSString *_name;
  4. int _age;
  5. int _height;
  6. int _weight;
  7. }
  8. @end
  9. @interface Testviewcontroller:uiviewcontroller
  10. @property (nonatomic, retain) MyPerson *testperson;
  11. -(Ibaction) Onbtntest: (ID) sender;
  12. @end
  13. -(void) Testkvo
  14. {
  15. Testperson = [[MyPerson alloc] init];
  16. [Testperson addobserver:self forkeypath:@ "height" options:nskeyvalueobservingoptionnew Context:nil];
  17. }
  18. -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context
  19. {
  20. if ([KeyPath isequaltostring:@ "height"]) {
  21. NSLog (@ "Height is changed! new=%@", [change Valueforkey:nskeyvaluechangenewkey]);
  22. } else {
  23. [Super Observevalueforkeypath:keypath Ofobject:object Change:change Context:context];
  24. }
  25. }
  26. -(Ibaction) Onbtntest: (ID) Sender {
  27. int h = [[Testperson valueforkey:@ "height"] intvalue];
  28. [Testperson setvalue:[nsnumber numberwithint:h+1] forkey:@ "height"];
  29. NSLog (@ "Person height=%@", [Testperson valueforkey:@ "height"]);
  30. }
  31. -(void) dealloc
  32. {
  33. [Testperson removeobserver:self forkeypath:@ "height" context:nil];
  34. [Super Dealloc];
  35. }

The first section of code declares the MyPerson class, which has a _height attribute. There is a Testperson object pointer in Testviewcontroller.
In this method of TESTKVO, we register the observation of the height property of the Testperson object, so that when the height property of the Testperson changes, it will be notified. In this method, it is also required to pass the new value in dictionary through the nskeyvalueobservingoptionnew parameter.
Rewrite the ObserveValueForKeyPath:ofObject:change:context: method, the change in this method the Nsdictionary object contains the corresponding value.
It is important to emphasize that the KVO callback is to be called, the property must be modified by means of KVC, and the observer will not be notified if the other method of invoking the class is to modify the property.

The underlying implementation principle of IOS KVC & KVO

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.