Reference: Http://blog.csdn.net/yuquan0821/article/details/6646400/
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.
Second, how to use
The system framework already supports KVO, so programmers are very easy to use.
1. Register, specify the attributes of the viewer,
2. Implementing a callback method
3. Removal of observations (arc not required)
Three, example:
When a property of an object changes, it is displayed on the screen
As in the Money field below
@interface Model: nsobject
@property (nonatomic,assign)int money ;
@end
Registered Observer
[_mymodel addobserver:self forkeypath:@ ' money ' options: Nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:NULL];
Callback implementation
-(void) Observevalueforkeypath: (nsstring *) keypath ofobject: (ID) object change: ( Nsdictionary *) Change context: (void *) context
{
_moneyshow. Text = [[nsstring alloc]initwithformat:@ "%d",_mymodel. Money ];
}
Full code
#import "ViewController.h"@interfaceModel:nsobject@property (nonatomic,assign)intMoney ;@end@interfaceViewcontroller () {UILabel*_moneyshow; Model*_mymodel;}@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; _moneyshow= [[UILabel alloc]initwithframe:cgrectmake ( -, -, -, -)]; _moneyshow.backgroundcolor=[Uicolor Bluecolor]; [Self.view Addsubview:_moneyshow]; _mymodel=[Model Alloc]init]; _mymodel.money= -;//KVO[_mymodel addobserver:self Forkeypath:@" Money"options:nskeyvalueobservingoptionnew|Nskeyvalueobservingoptionold Context:null]; UIButton*BTN =[[UIButton alloc]init]; Btn.frame= CGRectMake ( -, -, -, -); [BTN Settitle:@"Add Money"Forstate:uicontrolstatenormal]; Btn.backgroundcolor=[Uicolor Redcolor]; [Btn addtarget:self Action: @selector (Addmoney) forcontrolevents:uicontroleventtouchupinside]; [Self.view addsubview:btn];}-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) context{_moneyshow.text= [[NSString Alloc]initwithformat:@"%d", _mymodel.money];}- (void) addmoney{_mymodel.money+= -;}- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end
Overview and use of KVO