Kvo of iOS development ———— communication methods

Source: Internet
Author: User

KVO is a key-value observer, which provides an observer pattern for listening to changes in the value of an object's properties, and can implement a communication relationship between an observer, an observer, and a plurality of receivers.


KVO the workflow:

1. the observed attribute changes ( The Cleanvalue of the child object changes)

2. The Observer hears the change of the attribute (KVO helps us to implement the observer's business logic)

3. The Observer invokes the Observer method to notify the receiver of the event (the Watcher notifies the babysitter)

4. The event receiver responds to this event.


Add the child's observer to the receiver class, the object writes self, and the following implements the Observer method, which changes the child's associated attribute value and finally manually removes the Observer


Related methods:

1. How to add observers:

_child : The person being observed

Addobserver: the recipient of the event

Options: represented in the Observer method Change the value that can be obtained in the parameter.

Context: passed Parameters

[_childaddobserver:selfforkeypath: @ "Cleanvalue"options:nskeyvalueobservingoptionnew Context:NULL];

2. How the Observer responds to events:

//keypath: The name of the property being monitored by the Observer

//object : The person being observed

//change : is a dictionary that provides information about KVO useful information, such as key:new represents the new value after the property changes, Key:old represents the old value before the property changes

- ( void ) Observevalueforkeypath: ( nsstring *) KeyPath Ofobject: ( id nsdictionary . Span class= "S1" style= "White-space:pre" >< nsstring *, id > *) Change context: ( void *) Context {}


Example: The child is dirty and needs a nanny to take care of it

To add an observer to the child, the recipient of the event is the nanny, who passes the attribute value of the child cleanliness to the babysitter, who responds to the child care method.

#import "Child.h" @implementation child-(instancetype) init {        if (self = [super init]) {                _cleanvalue = +;        _happyvalue = +;    }        [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (timeraction:) Userinfo:nil Repeats:yes];        return self;} -(void) Timeraction: (Nstimer *) Timer {        //1. Only two ways to set the property value can be heard by KVO//    (1) Using setter method//    (2) KVC        // This method can not be heard by KVO//    _cleanvalue--;//    _happyvalue--;        Self.cleanvalue = _cleanvalue-1;        Self.happyvalue = _happyvalue-1;    NSLog (@ "Cleanvalue:%li,happyvalue:%li", _cleanvalue, _happyvalue);        } @end



#import "Nanny.h" #import "Child.h" @implementation nanny-(Instancetype) Initwithchild: (Child *) Child {if (self = [s                Uper Init]) {_child = child;        Using KVO to monitor changes in the child's attribute values, it is necessary to add an observer to the child and must be able to monitor changes in the child's attribute values after registering the observer.         /* Register an observer with the observer to listen for changes in the properties of the observed person.         _CHILD: Observer Addobserver: The recipient of the event options: Represents a value that can be obtained in the change parameter of the Observer method. Context: Passed parameters */[_child addobserver:self forkeypath:@ "Cleanvalue" Options:nskeyvalueobservingoptio        Nnew Context:null];            [_child addobserver:self forkeypath:@ "Happyvalue" Options:nskeyvalueobservingoptionnew Context:NULL];    } return self; }-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<nsstring *,id> *) Change context: (void *) Context {//keypath: The name of the property being monitored by the Observer//object: The Observer//change: is a dictionary that provides useful information about KVO, such as key:        New represents the value of the property after the change, Key:old represents the old value NSLog (@ "%@", change) before the property changes; if ([KeyPath isequaltostring:@ "Cleanvalue"]) {NSNumber *newvalue = change[@ "new"];            if ([NewValue IntegerValue] < 95) {//Nanny for child Dirty event handling code NSLog (@ "Nanny to wash Children in vain");                                _child.cleanvalue = 100;        }} else if ([KeyPath isequaltostring:@ "Happyvalue"]) {nsnumber *newvalue = change[@ "new"];            if ([NewValue IntegerValue] < 90) {//Nanny for child Dirty event handling code NSLog (@ "Nanny tease children Happy");                                _child.happyvalue = 100;    }}//With KVO also realizes the communication between the child and the nanny, the child can be separated from the nanny, to be decoupled, if you want to change a child-care class, just add the observer in the class, and the implementation of the Observer method is possible. }-(void) Dealloc {//Before the Nanny object is released, remove the Observer.    Arc can't help us finish.    [_child removeobserver:self forkeypath:@ "Cleanvalue"];    [_child removeobserver:self forkeypath:@ "Happtvalue"]; } @end



Kvo of iOS development ———— communication methods

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.