RAC的几种用法

#import 

替换代理

代理方法大家都理解,很简单。但是,代理很麻烦。要用代理,要经过以下步骤

  • 1.在view中定义协议(protocol),然后写代理方法,添加代理属性,然后实现代理方法
  • 2.在需要的地方,我们要遵守代理,然后将代理方法实现出来。

但是,如果使用rac就没有那么复杂了。

  • 1.在view中将btn的点击方法clickBtn实现
  • 2.在需要的地方直接调用clickBtn就好了。
[[self.hxView rac_signalForSelector:@selector(btnClick:)] subscribeNext:^(RACTuple * _Nullable x) {
     NSLog(@"收到信号了");
}];

当点击按钮的时候,rac就会收到点击的信号,然后在block中回调。

替换KVO

rac替换KVO,要引入一个框架

#import 

然后,我们就可以直接使用了。比如我们要对一个view的frame进行监听,下面是两种写法:

- (void)demoKVO
{
    [self.hxView rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:self block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
        
    }];
    
    [[self.hxView rac_valuesForKeyPath:@"frame" observer:self] subscribeNext:^(id  _Nullable x) {
        
    }];
}

替换按钮的点击方法

我们写按钮的点击方法,一般如下

[_btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];

如果使用RAC的话,如下:

- (void)targetDemo
{
    [[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
    }];
}

这样的话,我们根本不需要再另外写一个方法,我们的点击调用直接就在block中出现。

替换通知

通知的改变不是很大,只是把selector出的方法放进了block中

- (void)notificationDemo
{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"%@", x.userInfo);
    }];
}

监听textField的文字输入

在OC的时候,我们如果要监听textField的输入的每一个字符,我们可能要使用通知。还有字符串的长度什么的,我们还要遵守代理方法之类的。但是,到了RAC中,就简单了很多。

- (void)textFieldDemo
{
    [_textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@", x);
    }];
}

定时器

我们一般使用定时器,都是把它runloop中,如下:

- (void)timerDemo
{
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

        // 要想线程不死,只能使线程有执行不完的方法
        [[NSRunLoop currentRunLoop] run];
    }];
    [thread start];
}

在RAC中,就简单了很多

- (void)timerDemo
{
    [[RACSignal interval:1.0 onScheduler:[RACScheduler scheduler]] subscribeNext:^(NSDate * _Nullable x) {
        NSLog(@"%@----------%@", x, [NSThread currentThread]);
    }];
}

就这样吧。都是一些简单的用法。

你可能感兴趣的:(RAC的几种用法)