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
Three, example:
Suppose a scenario where the price of a stock is displayed on the current screen, and when the stock price changes, the real-time display updates its price.
1. Define Datamodel,
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- @interface Stockdata:nsobject {
- NSString * STOCKNAME;
- float price;
- }
- @end
- @implementation StockData
- @end
2. Define this model as the controller's property, instantiate it, listen to its properties, and display it in the current view
[CPP]View Plaincopy
- -(void) Viewdidload
- {
- [Super Viewdidload];
- STOCKFORKVO = [[StockData alloc] init];
- [Stockforkvo setvalue:@"searph" forkey:@"StockName"];
- [Stockforkvo setvalue:@"10.0" forkey:@"price"];
- [Stockforkvo addobserver:self forkeypath:@"Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:null];
- MyLabel = [[UILabel alloc]initwithframe:cgrectmake (100, 100, 100, 30)];
- Mylabel.textcolor = [Uicolor Redcolor];
- MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
- [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
[CPP]View Plaincopy
- -(void) buttonaction
- {
- [Stockforkvo setvalue:@"20.0" forkey:@"price"];
- }
4. Implementing a callback method
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: ( void *) Context
- {
- if ([KeyPath isequaltostring:@"Price"])
- {
- MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
- }
- }
5. Increased observation and cancellation of observations are in pairs, so it is necessary to remove the observer at the last
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- -(void) Dealloc
- {
- [Super Dealloc];
- [Stockforkvo removeobserver:self forkeypath:@"Price"];
- [Stockforkvo release];
- }
Four, summaryKvo This encoding method is very simple to use, it is suitable with Datamodel modified, the uiview caused by the change in this case, as the above example, when the value of the property changed, the listener will be immediately notified.
Overview and use of IOS:KVO