Understanding of iOS development-KVC and KVO

Source: Internet
Author: User

KVC and Kvo look very professional, in fact, it is relatively simple to use, KVC (key-value coding) can be understood as a key-value pair encoding, if the basic type of the object, then the key value pair encoding is actually not the same as the Get,set method, if the property is another object, Then found that KVC used to be very handy, KVO (Key-value observing) is a key-value pair of the Observer mode, if the object's property changes, then the Observevalueforkeypath event will be triggered , This notification feature of KVO allows us to save unnecessary code during development and improve development efficiency.

KVC Key-value pair encoding

KVC operation method is provided by the Nskeyvaluecoding protocol, NSObject implementation of this Protocol, that is, if the object is NSObject sub-object then support KVC operation, KVC has two methods of operation, one is to set the value, one is to take the value, Can be understood as getter and setter, but slightly different, there are two ways to set the value of an object, SetValue: attribute value Forkey: Property name (General settings, such as set Nsstring,nsnumber, etc. basic class types, Setetvalue: Property value Forkeypath: Attribute path (defines two objects, person and Book,person have a property of type book, this method can be used if you need to set the value of book in person), There are also two types of Valueforkey read: property name, Valueforkeypath: property name.

Code in Person.h:

  person.h//  bugdemo//http://www.cnblogs.com/xiaofeixiang///  Created by Keso on 15/2/8.//  Copyright (c) 2015 Keso. All rights reserved.//#import <Foundation/Foundation.h> #import "Book.h" @interface Person:nsobject@property ( strong,nonatomic) NSString *name; @property (strong,nonatomic) book  *book; @end

Code in Book.h:

  book.h//  bugdemo//http://www.cnblogs.com/xiaofeixiang///  Created by Keso on 15/2/8.//  Copyright (c) 2015 Keso. All rights reserved.//#import <Foundation/Foundation.h> @interface book:nsobject@property (strong,nonatomic) NSString *bookname; @end

The type of the book property in person is the book type, which looks at the simple invocation in the main function:

      Person *person=[[person Alloc]init];        [Person setvalue:@ "flyelephant" forkey:@ "Name"];        Book *book=[[book Alloc]init];        Person. Book=book;        Path settings        [person setvalue:@ "Tianya Moon Knife" forkeypath:@ "book.bookname"];        NSLog (@ "%@", [Person valueforkey:@ "Name"]);        NSLog (@ "%@", book. BookName);        NSLog (@ "%@", [Person valueforkeypath:@ "book.bookname"]);        NSLog (@ "%@", person. Book.bookname);

The final printing results are flyelephant and the end of the moon knife, it is necessary to note that the need to assign an object to the person in the book attribute, otherwise it will not succeed:

   Book *book=[[book Alloc]init];        Person. Book=book;
KVO Observer Pattern

Key-value Observing (KVO) is built on the KVC, can observe the change of the KVC key path value of an object, the next instance is implemented in the viewdidload of the view in iOS, similar to KVC, but can listen to the change of value, It's easy to implement Addobserver add observation,Observevalueforkeypath observe the events after the change, and finally need to destroy the following listening events, the concept is so simple, specific can look at:

New blogger (blogger) and article (article) classes:

Article.h statement:

  article.h//  kvdemo//http://www.cnblogs.com/xiaofeixiang///  Created by Keso on 15/2/8.//  Copyright (c) 2015 Keso. All rights reserved.//#import <Foundation/Foundation.h> @interface article:nsobject@property (strong,nonatomic ) NSString *articlename; @end

Blogger.h Code:

  bloger.h//  kvdemo//http://www.cnblogs.com/xiaofeixiang///  Created by Keso on 15/2/8.//  Copyright (c) 2015 Keso. All rights reserved.//#import <Foundation/Foundation.h> #import "Article.h" @interface Blogger: Nsobject@property (strong,nonatomic) nsstring *name; @property (strong,nonatomic) nsstring *url; @property (Strong, nonatomic) article *myarticle; @end

Then drag a button and a TextField text box in the storyboard and then click on the text box to change it:

First add the following code to the Viewdidload and note the Addobserver method:

    _blogger=[[blogger Alloc]init];        Set name    [_blogger setvalue:@ "Flyelephant" forkey:@ "name"];    Set URL    [Self.blogger setvalue:@ "Http://www.cnblogs.com/xiaofeixiang" forkey:@ "url"];    Set the Observer, the object form of the options notification    [Self.blogger addobserver:self forkeypath:@ "Name" options:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil];    Set Text    [_mytextfield settext:[_blogger valueforkey:@ "Name"];   Self. Article=[[article Alloc]init];        [Self.blogger setvalue:self. Article forkey:@ "Myarticle"];        [Self.blogger setvalue:@ "KVC and Kvo's understanding" forkeypath:@ "Myarticle.articlename"];

button click event:

-(Ibaction) Blogobserver: (ID) Sender {      NSLog (@ "Blogobserver");    [Self.blogger setvalue:@ "Keso" forkey:@ "Name"];}

To implement KVO in OC, the Nskeyvalueobserving protocol must be implemented, but NSObject has implemented the protocol and directly rewrites Observevalueforkeypath:

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{    NSLog (@ "Observevalueforkeypath");    if ([KeyPath isequaltostring:@ "name"]) {//         [_mytextfield settext:[_blogger valueforkey:@ "name"];          [_mytextfield Settext:_blogger. Myarticle.articlename];}    }

Finally, the listener event is destroyed:

-(void) didreceivememorywarning {    [super didreceivememorywarning];    Dispose of any resources the can be recreated.    [Self.blogger removeobserver:self forkeypath:@ "Name"];}

Final results:

Understanding of iOS development-KVC and KVO

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.