导入pod ‘ReactiveObjC’,’~>3.0.0’
头文件 #import <NSObject+RACKVOWrapper.h> #import <ReactiveObjC.h>
KVO与RAC 对比
KVO
- (void)viewDidLoad {
[super viewDidLoad];
_p = [[Person alloc] init];
//添加观察者
[_p addObserver:self forKeyPath:NSStringFromSelector(@selector(name)) options:(NSKeyValueObservingOptionNew) context:nil];
//NSKeyValueObservingOptionNew是接受最新值 默认就是new ====name是Person类里的nsstring类型属性
}
//改变的回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"\n--keyPath:%@\n--object:%@\n--change:%@\n",keyPath,object,change);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
static int a ;
_p.name = [NSString stringWithFormat:@"%d",a++];
}
运行
RAC
- (void)viewDidLoad {
[super viewDidLoad];
_p = [[Person alloc] init];
[[_p rac_valuesForKeyPath:NSStringFromSelector(@selector(name)) observer:nil]/*观察Person中name属性的变化*/ subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);//上面类似block传值 值传入x
}];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
static int a;
_p.name = [NSString stringWithFormat:@"%d",a++];
}
//将回调与创建观察者放在一个代码块完成,提高聚合性
运行效果