RAC学习记录(2)

简单的使用下RAC

  1. 代替KVO
- (void)kvo {
    [RACObserve(self, name) subscribeNext:^(id  _Nullable x) {
        NSLog(@"x:%@",x);
    }];
}

系统的写法

[self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld| NSKeyValueObservingOptionNew context:NULL];

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

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"name"];
}


RACkvo写法相比于系统代码高聚合低耦合了,也不用移除监听者

2.代替targetAction

- (void)targetAction
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(100, 100));
    }];
    
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"x:%@",x);
    }];
}

3.代替通知

{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"%@",x);
    }];
}

4.代替代理

 [[self rac_signalForSelector:@selector(textViewDidChange:) fromProtocol:@protocol(UITextViewDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
        NSLog(@"%@",x);
    }];
    self.textView.delegate = self;

5.代替手势

- (void)tap {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [self.view addGestureRecognizer:tap];
    
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        NSLog(@"%@",x);
    }];
}
  1. 代替定时器
  self.disposable = [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
        NSLog(@"%@",x);
        [self.disposable dispose];
    }];
    

7.监听某个方法被调用

- (void)signalForSelector
{
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(RACTuple * _Nullable x) {
        NSLog(@"xx------%@",x);
    }];
}

RAC的骚操作多的很,也搞不完。下一章节搞RACSignal

以上demo地址 demo

你可能感兴趣的:(RAC学习记录(2))