iOS 监听回调机制KVO实例
监听某个对象,如果这个对象的数据发生变化,会发送给监听者从而触发回调函数
[self.beanaddObserver:selfforKeyPath:@"data"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL];
这个就是注册监听,这个@“data”作为标识符方便回调函数辨认
-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context { if([keyPathisEqualToString:@"data"]) { self.label.text=[self.beanvalueForKey:@"data"]; } }
这个就是回调函数,分辨是哪个对象发生变化,然后给与相应的处理
-(void)viewWillDisappear:(BOOL)animated{ [self.beanremoveObserver:selfforKeyPath:@"data"]; }
既然有注册监听还记得解除监听
以下是完整例子代码
// //ViewController.m //First // //Createdbyshanreal-iOSon17/10/16. //Copyright©2017年shanreal.LongZhenHao.Allrightsreserved. // #import"ViewController.h" #import"TestBean.h" @interfaceViewController() @property(nonatomic,strong)UILabel*label; @property(nonatomic,strong)UIButton*btn; @property(nonatomic,strong)TestBean*bean; @end @implementationViewController -(void)viewDidLoad{ [superviewDidLoad]; //Doanyadditionalsetupafterloadingtheview. self.bean=[[TestBeanalloc]init]; [self.beansetValue:@"1"forKey:@"data"]; self.label=[[UILabelalloc]initWithFrame:CGRectMake(10,30,100,30)]; self.label.textColor=[UIColorblackColor]; self.label.text=[self.beanvalueForKey:@"data"]; [self.viewaddSubview:self.label]; self.btn=[[UIButtonalloc]initWithFrame:CGRectMake(10,100,200,30)]; [self.btnsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal]; [self.btnsetTitle:@"chanagedata"forState:UIControlStateNormal]; [self.btnaddTarget:selfaction:@selector(clickAction)forControlEvents:UIControlEventTouchUpInside]; [self.viewaddSubview:self.btn]; } -(void)viewWillAppear:(BOOL)animated{ [self.beanaddObserver:selfforKeyPath:@"data"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL]; } -(void)clickAction{ intdata=[[self.beanvalueForKey:@"data"]intValue]+1; self.bean.data=[NSStringstringWithFormat:@"%d",data]; } -(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context { if([keyPathisEqualToString:@"data"]) { self.label.text=[self.beanvalueForKey:@"data"]; } } -(void)viewWillDisappear:(BOOL)animated{ [self.beanremoveObserver:selfforKeyPath:@"data"]; } @end #import@interfaceTestBean:NSObject{ NSString*data; } @property(nonatomic,assign)intid; @property(nonatomic,strong)NSString*data; @end #import"TestBean.h" @implementationTestBean @end
以上这篇iOS监听回调机制KVO实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。