您的位置:首页 > Web前端 > React

响应式编程 RAC(ReactiveCocoa)初步学习

2019-05-07 11:00 281 查看

导入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++];
}

//将回调与创建观察者放在一个代码块完成,提高聚合性
运行效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: