iOS 监听回调机制KVO实例
程序员文章站
2023-12-16 21:06:16
监听某个对象,如果这个对象的数据发生变化,会发送给监听者从而触发回调函数
[self.bean addobserver:self forkeypath:@"dat...
监听某个对象,如果这个对象的数据发生变化,会发送给监听者从而触发回调函数
[self.bean addobserver:self forkeypath:@"data" options:nskeyvalueobservingoptionnew|nskeyvalueobservingoptionold context:null];
这个就是注册监听,这个@“data”作为标识符方便回调函数辨认
-(void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context { if([keypath isequaltostring:@"data"]) { self.label.text = [self.bean valueforkey:@"data"]; } }
这个就是回调函数,分辨是哪个对象发生变化,然后给与相应的处理
-(void)viewwilldisappear:(bool)animated{ [self.bean removeobserver:self forkeypath:@"data"]; }
既然有注册监听还记得解除监听
以下是完整例子代码
// // viewcontroller.m // first // // created by shanreal-ios on 17/10/16. // copyright © 2017年 shanreal.longzhenhao. all rights reserved. // #import "viewcontroller.h" #import "testbean.h" @interface viewcontroller () @property(nonatomic,strong)uilabel* label; @property(nonatomic,strong)uibutton* btn; @property(nonatomic,strong)testbean* bean; @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; // do any additional setup after loading the view. self.bean = [[testbean alloc]init]; [self.bean setvalue:@"1" forkey:@"data"]; self.label = [[uilabel alloc]initwithframe:cgrectmake(10, 30, 100, 30)]; self.label.textcolor = [uicolor blackcolor]; self.label.text = [self.bean valueforkey:@"data"]; [self.view addsubview:self.label]; self.btn = [[uibutton alloc] initwithframe:cgrectmake(10, 100, 200, 30)]; [self.btn settitlecolor:[uicolor blackcolor] forstate:uicontrolstatenormal]; [self.btn settitle:@"chanage data" forstate:uicontrolstatenormal]; [self.btn addtarget:self action:@selector(clickaction) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:self.btn]; } -(void)viewwillappear:(bool)animated{ [self.bean addobserver:self forkeypath:@"data" options:nskeyvalueobservingoptionnew|nskeyvalueobservingoptionold context:null]; } -(void)clickaction{ int data = [[self.bean valueforkey:@"data"] intvalue]+1; self.bean.data = [nsstring stringwithformat:@"%d",data]; } -(void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context { if([keypath isequaltostring:@"data"]) { self.label.text = [self.bean valueforkey:@"data"]; } } -(void)viewwilldisappear:(bool)animated{ [self.bean removeobserver:self forkeypath:@"data"]; } @end #import <foundation/foundation.h> @interface testbean : nsobject{ nsstring* data; } @property(nonatomic,assign)int id; @property(nonatomic,strong)nsstring* data; @end #import "testbean.h" @implementation testbean @end
以上这篇ios 监听回调机制kvo实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。