KVO removes class coupling through KVO.

Source: Internet
Author: User

KVO removes class coupling through KVO.
I. Overview

KVO, that is, Key-Value Observing, provides a mechanism. When the attribute of a specified object is modified, the object will receive a notification. In short, KVO automatically notifies the corresponding observer after the attribute of the specified object to be observed is modified.

Define A Class

@ Interface A: NSObject {
Int age;
}
@ End

 

2. Define A as the Controller attribute, instantiate it, listen to its attribute, 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 you click a button, call the buttonAction method to modify the attributes of the object.

-(Void) buttonAction
{
A. age + = 5;
}

4. Implement callback Methods

-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context
{
If ([keyPath isw.tostring: @ "age"])
{
[NSString StringWithFormat: @ "% d", a. age];
}
}

5. When the page exits, remove the observer.

Related Article

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.