Decoupling between classes by KVO

Source: Internet
Author: User

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

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.