ios-Observer pattern

Source: Internet
Author: User
Tags uikit


ios-Observer pattern


What is the observer pattern, that is, when the observed person has changed to be known by the Observer, and to make corresponding treatment. This article first uses the system, then realizes the observer pattern to understand its true principle.

Directory:

1. Use of System watcher mode

2. Custom Viewer Mode


Let's break down the use of observation modes in IOS programming:

-(void) Addobserver: ( NSObject *) Observer Forkeypath: (nsstring *) keypath options: (nskeyvalueobservingoptions Options Context: (void *) context;

This method is an extended class of nsobject, through which we can add observer observer to an object, and the observer is not concerned with the dynamic used by the observer, it only cares about the changes in some of the characteristics of the observed, so it is specified by KeyPath, when KeyPath is changed, You can change it. Notifies the observer that it is specified by option, and can also set any type of contextual context. What the Observer wants to do is to make a corresponding change.


-(void) Observevalueforkeypath: ( NSString *) keypath ofobject:(ID) object change: (nsdictionary *) Change context: ( void *) Context

This is also an extension of the Nsoject, when a feature of the observer has changed, the observer will invoke the function if it observes the feature.


Let's use the system-provided observer pattern: trace logs through function calls

#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller@property (nonatomic,assign) int observeredattr; @end

@interface Viewcontroller () @end//function call trace static variable traceint = 0; @implementation viewcontroller{    }-(void) viewdidload {    [super viewdidload];    Additional setup after loading the view, typically from a nib.    NSLog (@ "%d------%s", traceint++,__func__);    [Self addobserver:self forkeypath:@ "observeredattr" options:0 Context:nil];    Change the value of the observed variable so that it starts the operation of the Observer    [self changeobserverdattr]; -(void) changeobserverdattr{        NSLog (@ "%d------%s", traceint++,__func__);    self.observeredattr = 100;} -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{    NSLog (@ "%d------%s", traceint++,__func__);}

Results:

2015-04-02 21:03:06.366observer[928:30124] 0-------[Viewcontroller Viewdidload]

2015-04-02 21:03:06.367Observer [928:30124] 1-------[Viewcontroller changeobserverdattr]

2015-04-02 21:03:06.367 observer[928:30124] 2-------[Viewcontroller ObserveValueForKeyPath:ofObject:change:context :]


As can be seen in the results, add the observer, set it to itself, change the observed attribute, and invoke the observed method.


Custom Observer Mode:

The design of the observed person:

Header file:

#import <Foundation/Foundation.h> @interface observeredobject:nsobject@property (nonatomic,assign) int observeredattr;  observed attribute//Add observer to List-(void) Addobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) KeyPath; @end

Implementation file:

#import "ObserveredObject.h" #import "ObserverObject.h" @implementation observeredobject{//Observer queue Dictionary Nsmutabledictiona Ry *_oberverqueue;}    -(Instancetype) init{if (self= [Super init]) {_oberverqueue = [[Nsmutabledictionary alloc]init]; } return self;} Put the observer in the Observer Dictionary by path as the value, observer as Object-(void) Addobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) keypath{NSLog    (@ "------%s", __func__); [_oberverqueue setobject:observer Forkey:keypath];}    The set method of the overridden property-(void) setobserveredattr: (int) observeredattr{NSLog (@ "------%s", __func__);        if (observeredattr!=_observeredattr) {Nsarray *allkey = [_oberverqueue AllKeys]; for (int i= 0; i<allkey.count; i++) {if ([Allkey[i] isequaltostring:@ "observeredattr"]) {Ob                Serverobject *observer = [_oberverqueue objectforkey:@ "observeredattr"];            [Observer changedactionforpath:@ "observeredattr" andchangvalue:[nsstring stringwithformat:@ "%d", observeredAttr]];       } }}} @end 

The design of the viewer:

Header file:

#import <Foundation/Foundation.h> @interface observerobject:nsobject//This method when the observed property is changed-(void) Changedactionforpath: (NSString *) path Andchangvalue: (id) value; @end

Implementation file:

@implementation observerobject-(void) Changedactionforpath: (NSString *) path Andchangvalue: (ID) value{        NSLog (@ "- -----%s ", __func__);    if ([Path isequaltostring:@ "Observeredattr"]) {        NSLog (@ "The observeredattr of the object you are observing has changed%@", value);}    } @end

To customize the use of the Observer pattern:

    NSLog (@ "------%s", __func__);    Initialize the Observer    observeredobject *ed = [[Observeredobject alloc]init];    Initialize attribute ED.OBSERVEREDATTR when no observer is added    =;    Initialize Observer    Observerobject *ob = [[Observerobject alloc]init];    Add an observer for Ed and observe the properties of Observeredattr    [ed addobserver:ob forkeypath:@ "Observeredattr"];        Change the value of the attribute of the Observer    ed.observeredattr = 100;


Operation Result:

2015-04-02 21:34:23.933 target_action[1199:43513]-------[Viewcontroller Viewdidload]

2015-04-02 21:34:23.933 target_action[1199:43513]-------[observeredobject setobserveredattr:]

2015-04-02 21:34:23.933 target_action[1199:43513]-------[observeredobject Addobserver:forkeypath:]

2015-04-02 21:34:23.933 target_action[1199:43513]-------[observeredobject setobserveredattr:]

2015-04-02 21:34:23.933 target_action[1199:43513]-------[observerobject Changedactionforpath:andchangvalue:]

2015-04-02 21:34:23.933 target_action[1199:43513] The object of your observation observeredattr has changed. -



Summary:

Using the system's own observer pattern to use the Self.property method will not invoke the observer's observation method, the system's Self.property design principle is similar to the above custom Setmethod principle. Thank you.



ios-Observer pattern

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.