IOS-KVO overview and use, iOS-KVO overview and use

Source: Internet
Author: User

IOS-KVO overview and use, iOS-KVO overview and use
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.

Ii. Usage

The system framework already supports KVO, so it is very simple for programmers to use.

1. Registration, specifying the properties of the observer,

2. Implement callback Methods

3. Remove observation

Iii. Example: In a scenario, the stock price is displayed on the current screen. When the stock price changes, the stock price is updated in real time. The program directory is as follows:

The project procedure is as follows:

StockData. h

 

#import <Foundation/Foundation.h>@interface StockData : NSObject{     NSString * stockName;     float price;}@end

StockData. m

 

#import "StockData.h"@implementation StockData@end

 

The attribute defined here is defined in the ViewController. m file, but there is no content in ViewController. h, so it is not listed.

ViewController. m

# Import "ViewController. h "# import" StockData. h "@ interface ViewController () @ property (strong, nonatomic) UILabel * myLable; @ property (strong, nonatomic) StockData * stockforKVO; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; self. stockforKVO = [[StockData alloc] init]; [self. stockforKVO setValue: @ "searph" forKey: @ "stockName"]; [self. stockforKVO setValue: @ "10.0" forKey: @ "price"]; [self. stockforKVO addObserver: self forKeyPath: @ "price" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil]; self. myLable = [[UILabel alloc] initWithFrame: CGRectMake (100,100,100, 30)]; self. myLable. textColor = [UIColor redColor]; self. myLable. text = [NSString stringWithFormat: @ "% @", [self. stockforKVO valueForKey: @ "price"]; [self. view addSubview: self. myLable]; UIButton * B = [UIButton buttonWithType: UIButtonTypeRoundedRect]; B. frame = CGRectMake (0, 0,100, 30); B. backgroundColor = [UIColor redColor]; [B addTarget: self action: @ selector (buttonAction) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: B];}-(void) buttonAction {// click the button to change the value [self. stockforKVO setValue: [NSString stringWithFormat: @ "% d", arc4random () % 1000] forKey: @ "price"];}-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary <NSString *, id> *) change context :( void *) context {if ([keyPath isEqualToString: @ "price"]) {self. myLable. text = [NSString stringWithFormat: @ "% @", [self. stockforKVO valueForKey: @ "price"]; NSLog (@ "old data -- % @ --, new data -- % @ --", [change objectForKey: @ "old"], [change objectForKey: @ "new"]) ;}/ *-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {if ([keyPath isw.tostring: @ "price"]) {self. myLable. text = [NSString stringWithFormat: @ "% @", [self. stockforKVO valueForKey: @ "price"] ;}} * // *** remove the Observer */-(void) dealloc {[self. stockforKVO removeObserver: self forKeyPath: @ "price"];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end

 

The program Parsing is as follows:

1. Define DataModel, that is, the self-defined class
//StockData.h
#import <Foundation/Foundation.h>@interface StockData : NSObject{ NSString * stockName; float price;}@end
//StockData.m
#import "StockData.h"
@implementation StockData@end
2. Define this model as the Controller attribute, instantiate it, listen to its attributes, and display it in the current View.
- (void)viewDidLoad {    [super viewDidLoad];    self.stockforKVO=[[StockData alloc] init];    [self.stockforKVO setValue:@"searph" forKey:@"stockName"];    [self.stockforKVO setValue:@"10.0" forKey:@"price"];    [self.stockforKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];    self.myLable = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];    self.myLable.textColor = [UIColor redColor];    self.myLable.text = [NSString stringWithFormat:@"%@",[self.stockforKVO valueForKey:@"price"]];    [self.view addSubview:self.myLable];    UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];    b.frame = CGRectMake(0, 0, 100, 30);    b.backgroundColor=[UIColor redColor];    [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 {// click the button to switch between values [self. stockforKVO setValue: [NSString stringWithFormat: @ "% d", arc4random () % 1000] forKey: @ "price"];}

 

4. Implement callback Methods

-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary <NSString *, id> *) change context :( void *) context {if ([keyPath is1_tostring: @ "price"]) {self. myLable. text = [NSString stringWithFormat: @ "% @", [self. stockforKVO valueForKey: @ "price"]; NSLog (@ "old data -- % @ --, new data -- % @ --", [change objectForKey: @ "old"], [change objectForKey: @ "new"]) ;}/ *-(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {if ([keyPath isw.tostring: @ "price"]) {self. myLable. text = [NSString stringWithFormat: @ "% @", [self. stockforKVO valueForKey: @ "price"] ;}} */

 

5. Adding observation and canceling observation appear in pairs, so you need to remove the Observer at the end.
/*** Remove the Observer */-(void) dealloc {[self. stockforKVO removeObserver: self forKeyPath: @ "price"];}

 

Iv. SummaryKVO is a simple encoding method. It is applicable to the change of the UIVIew caused by the modification of datamodel. As in the preceding example, after changing the attribute value, the listener will be notified immediately. V. Procedures

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.