How to use IOS KVO

Source: Internet
Author: User

KVO (Key Value observing) 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 value changes, 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:

  • by AddObserver:forKeyPath:options:context: Registering listeners for the listener (which is usually the data model)

  • Rewrite the listener's ObserveValueForKeyPath:ofObject:change:context: method

  • Recommended focus on iOS development:Iosdevtip

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#import <Foundation/Foundation.h> @interface account:nsobject#pragma Mark-Properties #pragma mark Balance @property (nonatomic,assign) float balance; @end


Account.m#import "Account.h" @implementation account@end


Person.h#import <Foundation/Foundation.h> @class account; @interface person:nsobject{    @private    int _ Age;} #pragma mark-Attribute #pragma mark name @property (nonatomic,copy) nsstring *name; #pragma mark account @property (Nonatomic,retain) Acco UNT *account; #pragma mark-public method #pragma mark displays personnel information-(void) showmessage; @end


Person.m#import "Person.h" #import "Account.h" @implementation person#pragma mark-public method #pragma mark show people Information-(void) showmessage{    NSLog (@ "name=%@,age=%d", _name,_age);} #pragma mark set up the personnel account-(void) Setaccount: (Accounts *) account{    _account=account;    Add a listener to account    [Self.account addobserver:self forkeypath:@ "balance" options:nskeyvalueobservingoptionnew Context:nil];} #pragma mark-override method #pragma mark overrides the Observevalueforkeypath method, which is notified when the account balance changes-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{    if ([KeyPath isequaltostring:@ "Balance"]) {//Here only handles Balance property          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 you do not need to call this here} @end


Main.m#import <Foundation/Foundation.h> #import "Person.h" #import "Account.h" int main (int argc, const char * Argv[]) {    @autoreleasepool {person        *person1=[[person alloc]init];        [Email protected] "Kenshin";        Account *account1=[[account Alloc]init];        account1.balance=100000000.0;        Person1.account=account1;        account1.balance=200000000.0;//Note that performing 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.

How to use IOS 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.