The internal implementation principle of KVO

Source: Internet
Author: User

Key-value Observing (KVO)

First we first understand the mechanism of the KVO, KVO: The mechanism by which the object is allowed to receive notifications when the properties of the specified object have been modified.

For example:

[Persion addobserver:self forkeypath:@ ' age ' options: Nskeyvalueobservingoptionold | nskeyvalueobservingoptionnew context:nil];

As long as the age attribute in the current class changes, it will trigger the following method

-(void) Observevalueforkeypath: (NSString *) keypath
Ofobject: (ID) object
Change: (nsdictionary *) change
Context: (void *) context

And don't forget to remove the listener in the Dealloc.

-(void) dealloc{

[self. Persion removeobserver: Self- forkeypath:@ "age"];

}

Here's how it's implemented

The above image shows that when a class is first monitored, the system dynamically creates a Nskvonotifying_xqpersion class that inherits Xqpersion at run time.

In this derived class, override the setter method of any of the observed properties in the base class to implement a true notification mechanism in the setter method.

The set method of the Listener property is overridden in this class to notify the listener

-(void) Setage: (int) Age

{

[Super Setage:age];

[Listener observevalueforkeypath:@ "age" ofobject:self change:@{} context:nil];

}

The internal implementation principle of 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.