KVC Brief Introduction

Source: Internet
Author: User

KVC Brief Introduction

First, KVC simple introduction

KVC key valued coding key value encoding

KVC indirect encoding by key value

Add:

The KVO, the key valued observer, is observed relative to the KVC. Listen for the properties of a model, as long as the value of the model property changes to notify you.

Second, the use of KVC

1.KVC Basic Usage Introduction

(1) Code example:

Create a new command line project to demonstrate the use of KVC

When you are finished, add a person class for the project.

Add two attributes (name and age) to the person class, noting the type of these two properties.

1 #import <foundation/foundation.h>2 3 @interface person:nsobject4 @property (nonatomic,copy) nsstring *name;5 @ Property (nonatomic,assign) int age;6 @end

Import the class in the main file and encode the printout with the following code:

1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3  4 int main (int argc, const char * argv[]) 5 {6  7     @autoreleasepool {8          9         //nsnumber basic data type         //nsvalue structure One person         *p1=[[person Alloc] Init];13         [P1 setvalue:@ "Yangyong" forkeypath:@ "name"];14         [p1 setvalue:@ "All" forkeypath:@ "age"];15         16 Person         *p2=[[person alloc]init];17         [P2 setvalue:@ "Heyun" forkeypath:@ "name"];18         [P2 setvalue:@ "" forkeypath:@ "Age"];19 NSLog         (@ "%@ %@ ", p1, [P2  valueforkeypath:@" name "]);     }22     return 0;23}

Tip: If you want to track print results and print in a given format, you can override the description method, which is overridden in the person.m file to observe the printed output.

1 #import "Person.h" 2 3 @implementation Person4-(NSString *) description5 {6     //Override description method, spell a string, output 7 by a given number     return [NSString stringwithformat:@ "<%@:%p>,{name:%@,age:%d}", [Self class],self,self.name,self.age];8} 9 @end

The printing results are as follows:

(2) Code Description:

KVC key valued coding key value encoding

1) When using KVC to indirectly modify object properties, the system automatically determines the type of object properties and completes the conversion. such as "23" in the program.

2) KVC If the object does not contain the specified key value when the value is taken by the key value path, it will automatically go inside the object to find the object properties

(3) Code development

Question: What if we need to generate only an array of name and print?

As usual, we can use a for loop to take out the values of the corresponding properties of the object elements in the array, as follows:

         Create an array that stores the person object and print        Nsarray *[email protected][p1,p2];        NSLog (@ "%@", persons);                Nsmutablearray *arraym=[nsmutablearray array];        For (person *p in persons) {            [Arraym addobject:[p valueforkeypath:@ ' name '];        }        NSLog (@ "%@", Arraym);

KVC provides us with a more convenient way to do this:

Tip: When you kvc a value by key-value path, if the object does not contain the specified key value, it automatically goes inside the object, looking for object properties

     Create an array that stores the person object and print        Nsarray *[email protected][p1,p2];        NSLog (@ "%@", persons);                Nsmutablearray *arraym=[nsmutablearray array];//for        (person *p in persons) {//            [Arraym addobject:[p valueforkeypath:@ "name"]];//        }        [Arraym addobject:[persons valueforkeypath:@ "name"]];        NSLog (@ "%@", Arraym);

The two methods print the same effect:

Use of 2.KVC

(1) Description (KVC in accordance with the value of the key value path, will automatically layer deep, get the corresponding key value)

(2) Code example:

On the basis of 1, a new class book is added, which sets a BookName property for the class.

The code for the Book.h file is as follows:

1 #import <foundation/foundation.h>2 3 @interface book:nsobject4 @property (nonatomic,copy) nsstring *bookname;5 @ End

Also override the description method in the BOOK.M file

1 #import "Book.h" 2 3 @implementation Book4-(NSString *) description5 {6     return [NSString stringwithformat:@ "<%@, %p>{bookname:%@} ", [Self class],self,self.bookname];7}8 @end

Add an object property of the book class to the Preson class, and let "everyone has one."

1 #import <foundation/foundation.h>2 @class book;3 @interface person:nsobject4 @property (nonatomic,copy) NSString *name;5 @property (nonatomic,assign) int age;6 @property (nonatomic,strong) book *book;7 @end

Main program code:

 1 #import <Foundation/Foundation.h> 2 #import "Person.h" 3 #import "Book.h" 4 5 int main (int argc, const char * AR         Gv[]) 6 {7 8 @autoreleasepool {9//NSNumber basic data type//Nsvalue structure 12 13 Person *p1=[[person alloc]init];14 [P1 setvalue:@ "Yangyong" forkeypath:@ "name"];15 [P1 setvalue:@ "All" fo         rkeypath:@ "Age"];16 book *b1 = [[Book alloc] init];17 b1.bookname = @ "IPhone"; p1.book = b1;19 Person *p2=[[person alloc]init];21 [P2 setvalue:@ "Heyun" forkeypath:@ "name"];22 [P2 Setv  alue:@ "forkeypath:@"];23 book *b2 = [[Book alloc] init];24 b2.bookname = @ "ios"; p2.book = b2;26 NSLog (@ "%@%@", p1, [p2 valueforkeypath:@ "name"]); 28 29//Create an array that stores the person object and  Print Nsarray *[email protected][p1,p2];31 NSLog (@ "%@", persons); Nsarray *arraym=[persons valueforkeypath:@ "book.BookName "];34 NSLog (@"%@ ", Arraym);}36 return 0;37} 

Printing results:

Description: Use KVC to take a deep nested path, as long as it is a path to the desired properties to take out. (. Can be understood as a path.) has been entered). can help us to code very convenient.

KVC Brief Introduction

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.