Understanding and using KVO mode inside iOS

Source: Internet
Author: User

Brief introduction

KVO is: Key-value Observing this is the full name of the English, it is clear that the meaning is that the corresponding property of the specified object changes, automatically notify the observer, plainly speaking is the decoupling mode for two classes.

Example

Let's look at an example:

There is a business class: Walker, within this class, is responsible only for handling business logic, such as parsing data from a server's JSON, or doing other business data processing.

There is another class: Viewcontroller, which is specifically responsible for interface interaction with an attempt to update. Among them, some of Walker's properties need to be displayed and updated in real time.

At present, as far as I can think of the methods have the following:

Method 1, a direct function call

inside Walker's class , you create a Viewcontroller object and then call Viewcontroller's modify interface method to pass the property value that needs to be changed as a parameter to the function.

This is most intuitive, as it does not need to go around any bend. But the worst way to do that. Because Walker and Viewcontroller these two classes are tightly coupled from this. Remember this sentence, the class that deals with business logic, the less you know about external things, the better. Even, to do external whether there is a VC (View Controller), how many VCs do not affect me. Assuming this is a project, programmer A is responsible for the processing of the business logic, and programmer B is responsible for the UI, then in this way, programmer A is subject to B, interfering with each other.

Method 2, using the message communication mechanism (nsnotification)

Build the message center Nsnotificationcenter inside Walker, and instantiate the VC object as observer. Center built in Walker or VC does not matter, specifically see my blog another article "Nsnotificationcenter Summary." This method is better than the previous method. But there is a big drawback: If Walker has a lot of properties to change and is very frequent, this is not a convenient way to pass a value. And, notice not, "after the instantiation of the VC object as observer", always escape in Walker inside the VC instantiation. is still coupled.

Method 3, using delegate

There are a lot of introductions about delegate, and there's not much to say here. But in this demand with delegate, a little "overkill" feeling, the cost is larger, and not intuitive.

Method 4, using KVO mode

All of the code will be implemented in Viewcontroller. For Walker, it does not know whether there is a VC outside, and how VC will use my attributes.

Code

9 #import <foundation/foundation.h>10 @interface walker:nsobject12 {     nsinteger _age;14     nsstring *_ name;15}16 @property (nonatomic) Nsinteger age;18 @property (nonatomic, retain) NSString *name;19-(ID) Initwithnam E: (NSString *) name Age: (Nsinteger) age;21 @end

#import "Walker.h" @implementation walker@synthesize age = _age; @synthesize name = _name;-(void) dealloc{    [_name Release];    [Super Dealloc];} -(ID) Initwithname: (NSString *) Name: (Nsinteger) age{    if (self = [super init]) {        _name = name;        _age = age;    }    return self  ;} @end

#import <UIKit/UIKit.h> #import "Walker.h" @class Walker; @interface viewcontroller:uiviewcontroller{    Walker *_walker;    UILabel *_agelabel;} @property (nonatomic, assign) Walker *walker; @end

 9 #import "ViewController.h" @interface Viewcontroller () @end14 @implementation ViewController16 @synthe Size Walker = _walker;18-(void) Dealloc21 {[_walker release];23 [_agelabel release];24 [Super Deallo c];25}26-(void) viewDidLoad28 {[Super viewdidload];30//Do any additional setup after loading the view, T Ypically from a nib.31 _walker = [[Walker alloc] initwithname:@ "Old man" age:25];32/* key steps */33 [_walker addobserv Er:self34 forkeypath:@ "Age" options:nskeyvalueobservingoptionnew36 Conte     xt:nil];37//ui initialization40 UIButton *btn = [UIButton buttonwithtype:uibuttontypecustom];41 [Btn Setframe:cgrectmake (+, +, +)];42 [btn setbackgroundcolor:[uicolor lightgraycolor]];43 [btn settitl e:@ "Increase 5 years old" forstate:uicontrolstatenormal];44 [btn addtarget:self45 Action: @selector (buttonpressed) Forc Ontrolevents:uicontroleventtouchupinside];47 [self.view addsubview:btn];48 _agelabel = [[UILabel alloc] Initwithframe:cgrectmake (40 ,];50 _agelabel.text = [NSString stringwithformat:@ "%@ present Age is:%d", _walker.name, _walker.age];51 _ag Elabel.backgroundcolor = [Uicolor clearcolor];52 [Self.view addsubview:_agelabel];53]}56-(void) butt onPressed58 {_walker.age + = 5;60}61//KVO function, as long as the KeyPath property of object changes, this function is called */63-(void) observevaluefor KeyPath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context64 {if ([Keypa Th isequaltostring:@ "age"] && object = = _walker) {_agelabel.text = [nsstring stringwithformat:@ '%@ now ages Yes:%d ", _walker.name, _walker.age];67}68}69-(void) didReceiveMemoryWarning73 {The" Super Didreceivememo rywarning];75/Dispose of any resources the can be recreated.76}77 @end

When the button is clicked, the system calls the Observevalueforkeypath: function, which should also be a callback function. Do a UI update inside the function. We have achieved this in a lightweight way.

Reproduced original address:

Http://www.cnblogs.com/wengzilin/p/3223770.html

Understanding and using KVO mode inside iOS

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.