IOS: Using KVO to monitor array changes in the controller

Source: Internet
Author: User

First, Introduction:

KVO is a way to dynamically monitor the change in the value of the property, using a very wide range of scenarios, here I only talk about how to listen to the changes in the controller Viewcontroller array.

Second, understand:

First we should know that KVO is not able to directly monitor the change of the controller Viewcontroller array, need to define the array in the model, then the controller Viewcontroller hold the model object, through which to listen.

Third, step:

<1> define a model class in the Controller Viewcontroller class, and declare a mutable array property in the class Modelarray and lazy loading, in fact, it is finally used as an array of controller Viewcontroller;

  #import  <uikit/uikit.h> @interface   Viewcontroller:uiviewcontroller   @end  /*  * * New definition of a model class  */  @interface   Model: NSObject  /*  * * variable array  */  @property (strong,nonatomic) nsmutablearray  *modelarray;   @end  
"ViewController.h"

Viewcontroller

@end

@implementation Model*/* * * * *-(Nsmutablearray *) modelarray{ if(! _modelarray) { = [Nsmutablearray array]; } return _modelarray;} @end

<2> holds the global object of model class in the Controller Viewcontroller;

#import " ViewController.h " @interface Viewcontroller () /* * *   */  *model; @end

<3> the 2nd step to create the object registration monitoring, the Listener property is the array modelarray, that is, Modelarray as KeyPath value, registration method;

-(voidvoid *) context;
// Register KVO Monitor [_model addobserver:self Forkeypath:@ "modelarray" options:nskeyvalueobservingoptionnew Context:nil];

<4> rewrite the listening method, change the listening value;

-(voidID)objectIDvoid *) context;
Overriding Listener methods
-(void) Observevalueforkeypath: (NSString *) keypath ofobject: (ID)object Change: ( Nsdictionary<nsstring *,ID> *) Change context: (void *) context{    if ([ KeyPath isequaltostring:@ "modelarray"]) {        NSLog (@ "%) LD", _model.modelarray.count);    }}

<5> remove monitoring, and finally release internal memory need to remove the monitoring

-(void) dealloc{    [_model removeobserver:self forkeypath:@ "modelarray" ];}

<6> Click the interface, add the simulation data to the array, and the method must be : -(Nsmutablearray *) Mutablearrayvalueforkeypath: (NSString *) KeyPath;

-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *)event{        * obj = [[NSObject alloc]init];    [[_model Mutablearrayvalueforkeypath:@ "modelarray"] addobject:obj];}

Four, Demo: (Every click, can listen to the number of arrays increased by 1)

Five, the complete code is as follows:

. h file

////ViewController.h//kvotest////Created by Xiahuan on 16/11/23.//Copyright 2016 Guangzhou Network Technology Co., Ltd. All rights reserved.//#import<UIKit/UIKit.h>@interfaceViewcontroller:uiviewcontroller@end/** * New definition of a model class in the controller*/@interfaceModel:nsobject/** Variable Array*/@property (strong,nonatomic) Nsmutablearray*Modelarray;@end

. m file

////VIEWCONTROLLER.M//kvotest////Created by Xiahuan on 16/11/23.//Copyright 2016 Guangzhou Network Technology Co., Ltd. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller ()/** * Hold model object*/@property (strong,nonatomic) Model*model;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //1. Create a Model object_model =[Model Alloc]init]; //2. Register KVO Monitor[_model addobserver:self Forkeypath:@"Modelarray"options:nskeyvalueobservingoptionnew Context:nil];}/** * 3. Override the Listening method*/-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nsstring *,ID> *) Change context: (void*) context{if([KeyPath isequaltostring:@"Modelarray"]) {NSLog (@"%ld", _model.modelarray.count); }}/** * 4. Remove monitoring*/-(void) dealloc{[_model removeobserver:self Forkeypath:@"Modelarray"];}/** 5. Simulate adding data to an array*/-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{nsobject*obj =[[NSObject alloc]init]; [[_model Mutablearrayvalueforkeypath:@"Modelarray"] addobject:obj];}@end@implementationModel/** Lazy Loading*/-(Nsmutablearray *) modelarray{if(!_modelarray) {_modelarray=[Nsmutablearray array]; }    return_modelarray;}@end

IOS: Using KVO to monitor array changes in the controller

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.