这篇文章将为大家详细讲解有关iOS如何监听回调机制KVO,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
监听某个对象,如果这个对象的数据发生变化,会发送给监听者从而触发回调函数
[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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。