About KVC and KVO knowledge points in iOS

Source: Internet
Author: User

First, Introduction

KVC/KVO is an implementation of the observer pattern, which is defined as part of the underlying framework in cocoa, in the form of nskeyvaluecoding/nskeyvalueobserving informal protocol implemented by the source NSObject class of things. From an agreement standpoint, KVC/KVO essentially defines a set of methods that let us follow and implement.
Of course, the KVC/KVO implementation of the fundamental is objective-c dynamic and runtime, which in the later part of the principle will be described in detail.
In addition, the KVC/KVO mechanism is inseparable from the implementation of accessor methods.

1, KVC Introduction

The full name is Key-value coding, translated into key value encoding. As the name implies, to a certain extent, the relationship with map is shallow. It provides a mechanism to access an object instance variable using a string instead of an accessor method.
2, KVO Introduction

The full name is Key-value observing, translated into key value observation. Provides a mechanism for notifying the current object when other object properties have been modified. The KVO mechanism is well suited to the communication between model and controller classes in the cocoa of the great line of MVC.

KVC defines a mechanism for accessing object properties by name, and the main ways to support such access are:

-(ID) Valueforkey: (NSString *) key;   -(void) SetValue: (ID) value Forkey: (NSString *) key;   -(ID) Valueforkeypath: (NSString *) keypath;   -(void

The key used in the front two methods is easier to understand, which is the string that corresponds to the property name to access.
The keypath used in the next two methods is a sequence of strings separated by a dot operator for accessing the specified property of an object. For example, KeyPath Address.street will access a street property contained in the Address property contained in the message receiving object. In fact, KeyPath is that we usually use the point operation to access the properties of an object that is written when the string.

If you want to modify the property values of an object

1. In general, use the set method of the object property directly to modify:

Student *stu =//    [stu Setage:ten];     ten;

2. But what if I don't know the object type? Then you can use the KVC key value encoding (key value Coding) to indirectly modify the object properties

The KVC is implemented by using strings to describe the properties that an object needs to modify.

Basic calls to KVC include: valueforkey: and Setvalue:forkey: sending a message to an object as a string

KVC General Usage:

/******************************** Create the Book.h file just to illustrate Forkeypath usage without implementing *********************************/#import<Foundation/Foundation.h>@interface Book:nsobject@property (nonatomic,assign)DoublePrice//the price of the book@end/******************************** Student.h file *********************************/#import<Foundation/Foundation.h>@class Book; @interface student:nsobject@property (nonatomic,assign)intAge//Student Age@property (nonatomic,copy) NSString *name;//Student Name@property (nonatomic,retain) book *book;//Students own Books//test Method- (void) test; @end/******************************** student.m file *********************************/#import"Student.h"#import"Book.h"@implementation Student- (void) test{Student*stu =[[Student alloc] init]; //1. Assigning a single value to a basic data type[Stu SetValue:@"John"Forkey:@"name"]; NSString*str = [Stu Valueforkey:@"name"];//str = John//2. Assigning a single value to an object type//SetValue The parameter is an ID type, so you first wrap the base data type as an object type[Stu setvalue:@TenForkey:@" Age"]; //after the object is removed from the key value, it is converted to a basic data type.    intage = [[Stu Valueforkey:@" Age"] Intvalue];//TenNSLog (@"%@%d", str,age);//John Ten//3. Batch assignment for basic data types and object types[Stu setvaluesforkeyswithdictionary:@{@" Age":@ -,@"name":@"Jim"}]; //Take all the values out of the key to the dictionaryNsdictionary *dic = [Stu dictionarywithvaluesforkeys:@[@"name",@" Age"]]; NSLog (@"%@", DIC);//Age = 20;name = Jim//4. Indirectly assign a value to the book object's Price propertyStu.book = [[Book alloc] init];//Create a Stu.book object//First method: Direct Assignment[Stu.book Setprice:20.00];//Price = 20.00//second way: Assigning values by key values[Stu.book setvalue:@30.00Forkey:@" Price"];//Price = 30.00//The Third Way: To assign a value through the path of a health[Stu setvalue:@ +Forkeypath:@"Book.price"];//Price = 40.00//The key value and the key path are equivalent to the file name and filename, then the key value path is a key value, so you can use the key value can be used when the key path instead of the second way can also be written as[Stu.book setvalue:@ -Forkeypath:@" Price"];//Price = 50.00NSLog (@"%.2f", Stu.book.price);//Test Output@end In addition: KVC also provides methods for manipulating arrays and some calculated parameters

2.KVO (key value observing) key-value observation mechanism, mainly used to monitor the change of object properties

Implementation: Adding listeners

Example: Teacher class to listen for changes in the value of the Name property in the student class

/* **************************** Student.h file ************************************ */  <Foundation/Foundation.h>//  declaring the listener's properties //  Test Listener Method -(  void) test; @end


/***************************** Student.h file *************************************/#import"Student.h"#import"Teacher.h"@implementation Student- (void) test{Student*stu =[[Student alloc] init]; //Assigning a value to the Name property using KVC[Stu SetValue:@"Chapter Three"Forkey:@"name"]; //implementation of teacher Class listener student property name Change//1. Creating Listener ObjectsTeacher *teacher =[[Teacher alloc] init]; //Addoberver is the NSObject classification method, so any object can add a listening method//2. Adding listener objects to the Student class teacher options parameter: Listening for new or old values//Forkeypath: Key Path Context: Contexts used in animations[Stu Addobserver:teacher Forkeypath:@"name"Options:nskeyvalueobservingoptionnew Context:nil];//only the new values are monitored here, of course, you can listen together Option:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold//Modifying the value of the Student Class Name property notifies the listener that the teacher object is then called in the teacher class.Stu.name =@"Reese";//the method of executing the listener after the value of the Listener object has changed} @end
/***************************** Teacher.h file *************************************/#import <foundation/ Foundation.h> @interface Teacher:nsobject@end
/***************************** teacher.m file *************************************/#import"Teacher.h"#import"Student.h"@implementation Teacher//Once you hear a change in the Name property value in the Student class, this method in the listener teacher class is invoked to illustrate//keypath = @ "name"; object is the Student class change: changes to whether the value passed to the new or old value or the old or new value corresponds to the option parameter in the Listener- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) context{NSLog (@"keypath:%@", KeyPath);//Keypath:nameNSLog (@"objcet:%@",Object);//object:studentNSLog (@"change:%@", change);//\U674E\U65AF characters are escaped} @end

/***************************** mian.m file *************************************/#import <foundation/foundation.h > #import "Student.h" int main (int argc, const char * argv[]) {    @autoreleasepool {                //test        Student *stu = [[Stud ENT alloc] init];        [Stu Test];    }    return 0;}

About KVC and KVO knowledge points in iOS

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.