iOS Learning note--objective-c KVC, KVO

Source: Internet
Author: User

Overview

Because OBJC is designed primarily based on Smalltalk, it has many dynamic features like Ruby and Python, such as dynamic typing, dynamic loading, dynamic binding, and so on. Today we highlight key-value coding (KVC), key-value monitoring (KVO) features in OBJC:

(Original address: http://www.cnblogs.com/kenshincui/p/3871178.html)

    1. Key value Encoding KVC
    2. Key-Value Monitoring KVO
Key value Encoding KVC

We know that in C # you can read and write properties of an object by reflection, which is sometimes especially handy because you can use strings to dynamically control an object. In fact, because of the language characteristics of OBJC, you can perform dynamic read and write properties without any action on the root, which is the key Value Coding (abbreviated as KVC).

The operation method of KVC is provided by the Nskeyvaluecoding protocol, and NSObject implements this protocol, that is to say, almost all the objects in OBJC support KVC operation, the common KVC operation method is as follows:

    • Dynamic settings: SetValue: Attribute value forkey: property name (for simple Path),setValue: Property value Forkeypath: Property path (for compound path, For example, if person has an account type attribute, then Person.account is a composite attribute)
    • Dynamic read: valueforkey: Property name ,valueforkeypath: Property name (for compound path)

Here's an example to understand KVC

Account.h

  account.h//  kvcandkvo////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//<Foundation/Foundation.h>@account:nsobjectMark-Attribute Mark Balance @ balance; @end     

Account.m

  account.m//  kvcandkvo////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"Account.h"@implementation account@end 

Person.h

person.h//kvcandkvo////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>@Classaccount;@interface Person: nsobject{@_age;}  #pragma  #pragma mark name @ (nonatomic,copy) NSString *name; #pragma mark account @property  ( Nonatomic,retain) account *account;  #pragma mark-Public method  #pragma mark Display Personnel information-(    

Person.m

  person.m//  kvcandkvo////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//' Person.h '@implementationperson Mark-public method mark show people Information-(void) showmessage{NSLog (@"name=%@,age=%d", _name,_age);} @end       

Main.m

main.m//kvcandkvo////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>#import"Person.h"#import"Account.h"IntMainIntargcconst CHAR* argv[]) {@autoreleasepool {person *person1=[[person alloc]init]; [Person1 setvalue:@"Kenshin"forkey:@"Name"]; [Person1 setvalue:@28 forkey:@"Age"];Note Even though a private variable can still be accessed[Person1 ShowMessage];Results: name=kenshin,age=28NSLog (@"Person1 's name is:%@,age is:%@", Person1.name,[person1 valueforkey:@"Age"//result: Person1 ' s name is:kenshin,age is:28 account *account1= [[Account Alloc]init]; Person1.account=account1; //Note this step must first assign a value to the Account property, otherwise the following by path assignment is not successful, because it is nil, of course, this step can also be written as: [Person1 setValue: Account1 forkeypath:@ "Account"]; [person1 setvalue:@100000000.0 forkeypath:@ " Account.balance ",[[person1 Valueforkeypath:@ "account.balance" //result: Person1 ' s balance is:100000000.00 } return 0;}            

KVC is relatively simple to use, but how does it find a property to read? Specific lookup rules (assuming you are now reading A with KVC):

    • If the property is set dynamically, the call to the Seta method is preferred, and if there is no method then the search member variable _a is preferred, and if the search member variable A is still not present, then the Setvalue:forundefinedkey of the class will be called if the last search is still not found: Method ( Note that the search process can be set correctly regardless of whether these methods, the member variables are private, or public.
    • If it is a dynamic read property, it is preferable to call the A method (the getter method of property a), if no search is given, the member variable _a will be searched first, if it still does not exist, then the member variable A will be called, if it is still not found, then the valueforundefinedkey of this class is invoked: Method (Note that the search process, regardless of whether these methods, the member variables are private or public can be read correctly);
Key-Value Monitoring KVO

We know that there is a two-way binding mechanism in WPF and Silverlight that, if the data model is modified, is immediately reflected in the UI view, similar to today's more popular MVVM design pattern-based front-end framework, such as Knockout.js. In fact, in OBJC Zhongyuan support this mechanism, it is called Key Value observing (abbreviated KVO). KVO is actually an observer pattern that makes it easy to separate the view component from the data model, and when the data model's property values change, the view component as the listener is fired, and the listener itself is invoked when fired. To implement KVO in OBJC, the Nskeyvalueobserving protocol must be implemented, but fortunately NSObject has implemented the protocol, so OBJC can be used by almost all KVO objects.

The common methods for using KVO operations in OBJC are as follows:

    • Register the listener for the specified key path: addObserver:forKeyPath:options:context:
    • Delete the listener for the specified key path: removeobserver:forkeypath,removeObserver:forKeyPath:context:
    • Callback Listener: observeValueForKeyPath:ofObject:change:context:

The use of the KVO is also relatively straightforward:

    1. by AddObserver:forKeyPath:options:context: Registering listeners for the listener (which is usually the data model)
    2. Rewrite the listener's ObserveValueForKeyPath:ofObject:change:context: method

Since we have not introduced the interface programming of iOS, here we continue to expand on the basis of the above example, assuming that when our account balance balance changes, we want users to be notified in time. So at this point the account is our listener, and we need the person to register it for monitoring (using addObserver:forKeyPath:options:context:); and the person as listener needs to rewrite its observeValueForKeyPath:ofObject:change:context: method, The Listener person Listener method (ObserveValueForKeyPath:ofObject:change:context:) is recalled when the listening balance has changed. The following code simulates the process above:

Account.h

  account.h//  kvcandkvo////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//<Foundation/Foundation.h>@account:nsobjectMark-Attribute Mark Balance @ balance; @end     

Account.m

  account.m//  kvcandkvo////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//"Account.h"@implementation account@end 

Person.h

person.h//kvcandkvo////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>@Classaccount;@interface Person: nsobject{@_age;}  #pragma  #pragma mark name @ (nonatomic,copy) NSString *name; #pragma mark account @property  ( Nonatomic,retain) account *account;  #pragma mark-Public method  #pragma mark Display Personnel information-(    

Person.m

person.m//kvcandkvo////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import"Person.h"#import"Account.h"@implementation person#pragmaMark-Public method#pragmaMark Displays personnel information-(void) showmessage{NSLog (@"Name=%@,age=%d", _name,_age);}#pragmaMark set up a personnel account-(void) Setaccount: (account *) account{_account=account;Add a listener to account[Self.account addobserver:self forkeypath:@"Balance"Options:nskeyvalueobservingoptionnew Context:nil];}#pragmaMark-Override Method#pragmaMark rewrites the Observevalueforkeypath method when the account balance changes and is notified here-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void*) context{if([KeyPath isequaltostring:@"balance"]) {//This only handles balance attribute NSLog (@"keypath=%@,object= %@,newvalue=%.2f,context=%@ ", Keypath,object,[[change objectforkey:@" new "] floatvalue],context);}} #pragma Mark Rewrite destruction Method-(void) dealloc{[self.account removeobserver:self forkeypath:@"balance" ]; //Remove listener//[super dealloc];//Note that arc is enabled and is not required to be called here } @end           

Main.m

main.m//kvcandkvo////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#import<Foundation/Foundation.h>#import "Person.h"  #import  " Account.h "int main (int ARGC, * argv[]) {@autoreleasepool {person *person1 =[[person Alloc]init]; [Email protected] //note execution to this step triggers the listener callback function ObserveValueForKeyPath:ofObject:change:context://Result: keypath= balance,object=<account:0x100103aa0>,newvalue=200000000.00,context= (NULL) return 0;}            

In the above code, we add a listener to the account's balance attribute when assigning an account to the person, and output the information that is heard in the listener callback method, while removing the listener when the object is destroyed, which constitutes a typical KVO application.

iOS Learning note--objective-c KVC, 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.