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.