KVO Use of objective-c syntax

Source: Internet
Author: User

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{    *  Stocknmae;     float Price ;} @end
#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

@interface Viewcontroller () @property (Nonatomic,strong) StockData *stcokforkvo; @property (nonatomic,strong) UILabel * MyLabel; @end

-(void) viewdidload {    [super viewdidload];    Self.stcokforkvo=[[stockdata Alloc]init];    [Self.stcokforkvo setvalue:@ "Searph" forkey:@ "Stocknmae"];    [Self.stcokforkvo setvalue:@ "10.0" forkey:@ "Price"];    [Self.stcokforkvo addobserver:self forkeypath:@ "Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:nil];        Self.mylabel=[[uilabel Alloc]initwithframe:cgrectmake (+, +, +)];    Self.mylabel.textcolor=[uicolor Redcolor];    self.mylabel.text= [NSString stringwithformat:@ "%@", [Self.stcokforkvo valueforkey:@ "Price"];    [Self.view AddSubview:self.mylabel];        UIButton *b=[uibutton Buttonwithtype:uibuttontyperoundedrect];    B.frame=cgrectmake (a);    B.backgroundcolor=[uicolor Bluecolor];    [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

-(void) buttonaction{    [Self.stcokforkvo setvalue:[nsstring stringWithFormat:@ "  %d", Arc4random ()%forkey:@"price"];}

4. Implementing a callback method

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (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:@" Old"],[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 " ];}

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.

KVO Use of objective-c syntax

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.