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