IOS development-understanding of KVC and KVO

Source: Internet
Author: User

IOS development-understanding of KVC and KVO
KVC and KVO look very professional. In fact, they are relatively simple to use. KVC (Key-value coding) can be understood as Key-value Pair encoding. If the basic type of the object is, then the key-value Pair encoding is actually no different from the get and set methods. If the attribute is another object, it is found that KVC is very easy to use, KVO (key-value observing) it is the observer mode of key-value pairs. If the object attribute changes, the observeValueForKeyPath event will be triggered. This notification feature of KVO saves unnecessary code during development, improved development efficiency. The KVC key-Value Pair encoding method is provided by the NSKeyValueCoding protocol. NSObject implements this Protocol. That is to say, if the object is a sub-object of NSObject, KVC operations are supported, KVC has two operation methods: Set Value and set value, which can be understood as getter and setter. But slightly different, there are two methods for setting object values, setValue: attribute value forKey: attribute name (for example, setting NSString, NSNumber, and other basic class types. setetValue: attribute value forKeyPath: attribute path (defines two objects, Person and Book, person has an attribute of the Book type. If you need to set the Book value in Person, you can use this method). Two types of valueForKey are read: property name, valueForKeyPath: attribute name. Person. code in 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; @ endBook. code in 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; @ The Book attribute type in endPerson is Book type. See the following simple calls in the main function: person * person = [[Person alloc] init]; [person setValue: @ "FlyElephant" forKey: @ "Name"]; Book * book = [[Book alloc] init]; person. book = book; // path setting [person setValue: @ "" forKeyPath: @ "Book. bookName "]; NSLog (@" % @ ", [person valueForKey: @" Name "]); NSLog (@" % @ ", book. bookName); NSLog (@ "% @", [person valueForKeyPath: @ "Book. bookName "]); NSLog (@" % @ ", person. book. bookName); the final printed result is FlyElephant and Tianya Mingyue Dao. Note that you must assign an object to the Book attribute in Person first, or else the Book attribute will fail: book * book = [[Book alloc] init]; person. book = book; KVO observer mode Key-Value Observing (KVO) is built on KVC to observe the changes in the KVC key path Value of an object, the following example is implemented in the ViewDidLoad of the image in iOS, which is similar to that of KVC. However, it is easy to add an addObserver to observe the changes in the listening value, observeValueForKeyPath: Observe the changed events and destroy the following listener events. The concept is as simple as this. For details, refer to: new Blogger (Blogger) and Article (Article) Class: 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; @ endBlogger. 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 story board, and then change the text box when you click it: first Add the following code to ViewDidLoad. Note the addObserver method: _ blogger = [[Blogger alloc] init]; // set the Name [_ blogger setValue: @ "FlyElephant" forKey: @ "Name"]; // set the Url [self. blogger setValue: @ "http://www.cnblogs.com/xiaofeixiang" forKey: @ "Url"]; // sets the object form of the observer, options notification [self. blogger addObserver: self forKeyPath: @ "Name" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil]; // set the text [_ myTextField setText: [_ blogger valueForKey: @ "Name"]; self. article = [[Article alloc] init]; [self. blogger setValue: self. article forKey: @ "MyArticle"]; [self. blogger setValue: @ "KVC and KVO Comprehension" forKeyPath: @ "MyArticle. articleName "]; click the event:-(IBAction) blogObserver :( id) sender {NSLog (@" blogObserver "); [self. blogger setValue: @ "Keso" forKey: @ "Name"];} to implement KVO in OC, The NSKeyValueObServing protocol must be implemented. However, NSObject has implemented this protocol and can directly rewrite observeValueForKeyPath: -(void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {NSLog (@ "observeValueForKeyPath "); if ([keyPath is1_tostring: @ "Name"]) {// [_ myTextField setText: [_ blogger valueForKey: @ "Name"]; [_ myTextField setText: _ blogger. myArticle. articleName] ;}} finally destroy the listener:-(void) didReceiveMemoryWarning {[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. [self. blogger removeObserver: self forKeyPath: @ "Name"];}

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.