One, overview
KVO, Key-value Observing, provides a mechanism for the object to receive notification when the properties of the specified object have been modified. Simply put, the KVO will automatically notify the appropriate observer when the property of the observed object has been modified each time it is specified.
Define a Class A
@interface A:nsobject {
int age;
}
@end
2. Define the properties of this a controller, instantiate it, listen to its properties, and display it in the current view
-(void) viewdidload
{
[Super Viewdidload];
A = [[A alloc] init];
A.age = 5;
[A addobserver:self forkeypath:@ "age" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:null];
MyLabel = [[UILabel alloc]initwithframe:cgrectmake (100, 100, 100, 30)];
Mylabel.textcolor = [Uicolor Redcolor];
MyLabel.Text = [NSString stringwithformat:@ "%d", a.age];
[Self.view Addsubview:mylabel];
UIButton * b = [UIButton buttonwithtype:uibuttontyperoundedrect];
B.frame = CGRectMake (0, 0, 100, 30);
[B addtarget:self Action: @selector (Buttonaction) forcontrolevents:uicontroleventtouchupinside];
[Self.view addsubview:b];
}
3. When the button is clicked, call the Buttonaction method to modify the object's properties
-(void) buttonaction
{
A.age + = 5;
}
4. Implementing a callback method
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context
{
if ([KeyPath isequaltostring:@ "Age"])
{
[NSString stringwithformat:@ "%d", a.age];
}
}
5. Finally, remove the viewer when the page exits
Decoupling between classes by KVO