iOS kvo 结合 FBKVOController 的使用
一:FBKVOControlloer是FaceBook开源的一个 在 iOS,maxOS上使用 kvo的 开源库;
提供了block和@selector(SEL) 的回调操作,很方便实用;
https://github.com/facebook/KVOController
二:示例:
fbKVO = [FBKVOController controllerWithObserver:self];
[fbKVO observe:personOne keyPath:@"pName" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) { //NSLog(@"%@ %@ %@",observer,object,change);
//Person *p = (Person *)object;
//self.title = p.pName;
self.title = change[NSKeyValueChangeNewKey]; }];
三:流程操作
1:创建 Person Object
#import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic,strong)NSString *pName; @end
2: 下载FBKVOController---导入FBKVOController.h .m文件 ARC环境
#import "FBKVOController.h"
#import "Person.h"
3:创建Person对象(被观察者),及FBKVOController对象(管理观察者与被观察者);
@interface RootViewController ()
{
Person *personOne;
FBKVOController *fbKVO;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"TEST"; listArray = [[NSMutableArray alloc]initWithCapacity:5];
[listArray addObject:@"FBKVOController"]; personOne = [[Person alloc]init];
personOne.pName = @"defaultName"; fbKVO = [FBKVOController controllerWithObserver:self];
[fbKVO observe:personOne keyPath:@"pName" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) { //NSLog(@"%@ %@ %@",observer,object,change);
//Person *p = (Person *)object;
//self.title = p.pName;
self.title = change[NSKeyValueChangeNewKey]; }]; /**
一:kvo值检测类型;
1: NSKeyValueObservingOptionNew 传递变化之后的值;
2: NSKeyValueObservingOptionOld 传递变化之前的值;
3: NSKeyValueObservingOptionInitial 观察者会在程序初始时,也就是观察变化之前,优化执行一次 观察动作;即上述执行上面 block操作一次;并且传递 默认的值,和以后传递 变化后的值;
4: NSKeyValueObservingOptionPrior 会调用两次观察者操作,值改变之前,值改变之后; 二:获取 kvo的值;
change[NSKeyValueChangeNewKey] 新值;
change[NSKeyValueChangeOldKey] 旧值; */ }
4:添加改变 被观察者 Person的pName属性值变化操作,然后在 观察者观察到 pName值发生变化时,改变 self.title的值
#pragma mark action 点击 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES]; int nums = arc4random()%10;
personOne.pName = [NSString stringWithFormat:@"newName%d",nums];
NSLog(@"new --> %@",personOne.pName);
}
//在 pName属性值发生变化时,改变self.title的值;
[fbKVO observe:personOne keyPath:@"pName" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) { //NSLog(@"%@ %@ %@",observer,object,change);
//Person *p = (Person *)object;
//self.title = p.pName;
self.title = change[NSKeyValueChangeNewKey]; }];
5:如果想移除观察者:
//三种方式任你选择;
[fbKVO unobserve:personOne];
[fbKVO unobserve:personOne keyPath:@"pName"];
[fbKVO unobserveAll];
6: 效果:
改变值之前
改变值之后