KVC & KVO Getting Started

Source: Internet
Author: User

KVC:

Brief introduction:

Full name Key-value Coding. KVC is a mechanism for indirectly accessing object properties (represented by strings) rather than directly invoking the object's accessor (Setter/getter) method or accessing the member object directly. The key value of the KVC must be lowercase, and the attribute or variable within the object. You can access some of the variables that are not exposed.

Use:

[_bank setValue:@ "I am Lee" forkey:@ "name"];   // Setting the value [_bank Valueforkey:@ "name"];  // Read Value

It can be seen that the use of KVC is very simple, but only KVC is not enough, but also need to combine KVO to do.

KVO:

Brief introduction:

Allows the object to accept a notification mechanism when the specified object's properties have been modified. Each time the specified object's properties are modified, the KVO automatically notifies the appropriate observer. The main use of KVO to implement object properties and variable monitoring. When there is a property change, KVO will provide an automatic message notification. Such an architecture has many benefits. First, developers do not need to implement the scenario themselves: send a message notification each time the property changes. This is the greatest advantage provided by the KVO mechanism. Since the scheme has been clearly defined, it can be easily adopted with framework-level support. Developers do not need to add any code, they do not need to design their own observer model, directly can be used in the project. Second, the KVO architecture is so powerful that it's easy to support multiple observers observing the same property, as well as related values. In general, it is not necessary to define the notification mechanism of the message, only to care about the change of the value of the object.

Use:

Defining Bank.h Files

// //   Bank.h//  testdemo////  Created by Stardust on 15-1-15.//  Copyright (c) 2015 COM. All rights reserved. // #import <Foundation/Foundation.h>@interface  bank:nsobject{    *  Name;} @property Nsinteger money; -(void) berobbed; @end

BANK.M file:

////BANK.M//Testdemo////Created by Stardust on 15-1-15.//Copyright (c) 2015 COM. All rights reserved.//#import "Bank.h"@implementationBank//@synthesize money;-(void) berobbed{Self.money= Self.money- -;}@end

APerson.h file:

// //   APeron.h//  testdemo////  Created by Stardust on 15-1-15.//  Copyright (c) 2015 COM. All rights reserved. // #import <Foundation/Foundation.h>@interface  aperon:nsobject@end 

APERSON.M file:

////aperon.m//Testdemo////Created by Stardust on 15-1-15.//Copyright (c) 2015 COM. All rights reserved.//#import "APeron.h"@implementationAperon-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) context{if([KeyPath isequaltostring:@"name"]) {NSLog (@"KVC old name was%@, new name is%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change objectforkey:nskeyvaluechangenewkey]); }    Else if([KeyPath isequaltostring:@" Money"]) {NSLog (@"KVC Old money was%@, new money is%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change objectforkey:nskeyvaluechangenewkey]); }    Else{NSLog (@"KVC old value was%@, new value is%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change objectforkey:nskeyvaluechangenewkey]); }}@end

Main file kvocontroller.m:

////KVOVIEWCONTROLLER.M//Testdemo////Created by Stardust on 15-1-15.//Copyright (c) 2015 COM. All rights reserved.//#import "KVOViewController.h"#import "Bank.h"#import "APeron.h"@interfaceKvoviewcontroller () @property Aperon*Aperson, @property Bank*Bank;@end@implementationKvoviewcontroller- (void) viewdidload {[Super viewdidload]; //Do any additional setup after loading the view._aperson=[[Aperon alloc]init]; _bank=[Bank Alloc]init]; [_bank Addobserver:_aperson Forkeypath:@"name"Options: (nskeyvalueobservingoptionold| Nskeyvalueobservingoptionnew) Context:@"Hello"]; [_bank Addobserver:_aperson Forkeypath:@" Money"Options: (nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold) Context:@"Hello2"]; [_bank Addobserver:_aperson Forkeypath:@"Jack"Options: (nskeyvalueobservingoptionold| Nskeyvalueobservingoptionnew) Context:@"Hello3"]; [_bank SetValue:@"I am Lee"Forkey:@"name"]; _bank.money=101;        [_bank berobbed]; NSLog (@"... %@", [_bank Valueforkey:@"name"]); //[_bank setvalue:@ "Tim Jack" forkey:@ "Jack"]; //This sentence is an error        

//must remove kvo, otherwise it may be error

[_bank removeobserver:_aperson forkeypath:@ "name"];

[_bank removeobserver:_aperson forkeypath:@ "Money"];

[_bank removeobserver:_aperson forkeypath:@ "Jack"];

}-(void) didreceivememorywarning {    [super didreceivememorywarning];     // Dispose of any resources the can be recreated.  }/*#pragma mark-navigation//in a storyboard-based application, you'll often want to do a little Preparation before navigation-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) Sender {    //Get the new View controller using [Segue Destinationviewcontroller].    Pass the selected object to the new view controller.} */ @end

Show Results:

 -- on- the  +: $:52.256testdemo[3442:634253] KVC old name is<NULL>,NewName isI am Lee -- on- the  +: $:52.257testdemo[3442:634253] KVC Old Money is 0,NewMoney is 101 -- on- the  +: $:52.257testdemo[3442:634253] KVC Old Money is 101,NewMoney is 1 -- on- the  +: $:52.258testdemo[3442:634253] ... I am Lee

Through the above can be seen, set Aperson to listen to the changes in the Bank object, monitoring changes in the processing of Aperson, as long as the Bank object is monitored in the value of change, whether it is directly set to change, or through KVC, can listen to get and execute the relevant monitoring logic. However, for non-existent values, such as the one commented in the main file code: "[_bank setvalue:@" Tim Jack "forkey:@" Jack "]," even if you can add a listener that does not exist, but when the corresponding KVC is called, it crash, This may be related to the KVC mechanism.

Reference:

1

KVC & KVO Getting Started

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.