This article turns from: Http://blog.csdn.net/yuquan0821/article/details/6646400/, 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 StockData
#import <Foundation/Foundation.h> @interface stockdata:nsobject{ nsstring *stocknmae; float price; @end
| 12345 |
#import "StockData.h"@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
| 1234 |
@interfaceViewController ()@property(nonatomic,strong)StockData *stcokForKVO;@property(nonatomic,strong)UILabel *mylabel;@end |
| 1234567891011121314151617181920 |
- (void)viewDidLoad { [superviewDidLoad]; self.stcokForKVO=[[StockData alloc]init]; [self.stcokForKVO setValue:@"searph"forKey:@"stockNmae"]; [self.stcokForKVO setValue:@"10.0"forKey:@"price"]; [self.stcokForKVO addObserver:selfforKeyPath:@"price"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil]; self.mylabel=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)]; self.mylabel.textColor=[UIColor redColor]; self.mylabel.text= [NSStringstringWithFormat:@"%@",[self.stcokForKVO valueForKey:@"price"]]; [self.view addSubview:self.mylabel]; UIButton *b=[UIButton buttonWithType:UIButtonTypeRoundedRect]; b.frame=CGRectMake(50, 50, 100, 30); b.backgroundColor=[UIColor blueColor]; [b addTarget:selfaction:@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{ [self.stcokforkvo setvalue:[nsstring stringwithformat:@ "%d", Arc4random ()%1000] forKey:@ " Price "];}
4. Implementing a callback method
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<nsstring *,id> *) Change context: (void *) context{ if ([KeyPath isequaltostring:@ "Price"]) { self.mylabel.text= [nsstring stringwithformat:@ "%@", [Self.stcokforkvo valueforkey:@ "Price"]; NSLog (@ "old data--%@--, new Data--%@--", [Change objectforkey:@ "OID"],[change objectforkey:@ "new"]);}
5. Increased observation and cancellation of observations are in pairs, so it is necessary to remove the observer at the last
-(void) dealloc{ [self.stcokforkvo removeobserver:self forkeypath:@ "price"];}
Talking about the KVO mode inside iOS