KVO 简单小例子

结合之前某智付项目  用到了监测 程序是否isLogin 登录状态 

在AppDelegate中 添加观察者

[[MobileBankSession sharedInstance] addObserver:self forKeyPath:@"isLogin" options:NSKeyValueObservingOptionNew context:nil];

当MobileBankSession(网络类)类中的isLogin值变化的时候会调用

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

做一些登出isLogin = NO;的操作  

比如显示侧边栏

}

小例子:

#import "ViewController.h"#import "Walker.h"@interface ViewController (){    UILabel *label;    Walker *walker;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    walker = [[Walker alloc] initWithName:@"Boss" age:45];  

//关键代码  添加观察者

  [walker addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];       

 label = [[UILabel alloc] init];   

 label.frame = CGRectMake(10, 80, 200, 60);    label.text = [NSString stringWithFormat:@"姓名:%@,年龄:%ld",walker.name,walker.age];    label.backgroundColor = [UIColor grayColor];    [self.view addSubview:label];            UIButton *button = [[UIButton alloc] init];    button.frame = CGRectMake(100, 200, 80, 80);    button.backgroundColor = [UIColor grayColor];    [button setTitle:@"年龄增加5岁" forState:UIControlStateNormal];    [button addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];}

//关键代码

/* KVO function, 只要object的keyPath属性发生变化,就会调用此函数*/- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary*)change context:(nullable void *)context;

{

if ([keyPath isEqualToString:@"age"] && object == walker){

label.text = [NSString stringWithFormat:@"姓名:%@,年龄:%ld",walker.name,walker.age];

}

}

- (void)btnAction{

walker.age += 5;

}

- (void)viewWillDisappear:(BOOL)animated{

[super viewWillDisappear:animated];

[walker removeObserver:self forKeyPath:@"age"];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end


KVO 简单小例子_第1张图片

点击了按钮之后,系统会调用 observeValueForKeyPath :函数,这个函数应该也是回调函数。在该函数内部做UI更新。我们以这种轻量级的方式达到了目的。


KVO 简单小例子_第2张图片
KVO中谁要监听谁注册,然后对响应进行处理,使得观察者与被观察者完全解耦。KVO只检测类中的属性,并且属性名都是通过NSString来查找,编译器不会检错和补全,全部取决于自己。

你可能感兴趣的:(KVO 简单小例子)