RAC 中的通知、代理、KVO, 基本事件、方法的监听

文章系列
《ReactiveCocoa 概述》
《RACSignal》
《RACDisposable》
《RACSubject、RACReplaySubject(内附冷信号和热信号的区别)》
《集合RACTuple、RACSequence》
《RAC 中的通知、代理、KVO, 基本事件、方法的监听》
《rac_liftSelector》
《RACMulticastConnection》
《RACCommand》
《RAC - 核心方法bind》
《RAC - 定时器》
《RACScheduler》
《RAC - 点击获取验证码 demo》
《RAC - 映射(Map & flattenMap)》
《RAC信号操作解释合集》
《RAC - 信号的生命周期》

  • rac_addObserverForName(通知)

OC正常写法(需要自己单独实现noti: 方法去处理通知事件)

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:@"noti" object:nil];

OC 中使用RAC 写法

    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"noti" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
          // 处理通知事件
    }];

↓rac_addObserverForName: 原理分析↓

- (RACSignal *)rac_addObserverForName:(NSString *)notificationName object:(id)object {
    @unsafeify(object);
    return [[RACSignal createSignal:^(id subscriber) {
        @strongify(object);
        // 内部封装的 KVO
        id observer = [self addObserverForName:notificationName object:object queue:nil usingBlock:^(NSNotification *note) {
            // 发送监听信息
            [subscriber sendNext:note];
        }];

        return [RACDisposable disposableWithBlock:^{
            // 在取消订阅后, 移除观察者
            [self removeObserver:observer];
        }];
    }] setNameWithFormat:@"-rac_addObserverForName: %@ object: <%@: %p>", notificationName, [object class], object];
}
  • 代理

RACSubject 通常用来代替代理
rac_signalForSelector 也可以用做代理, 但是无法传值!
这里只说RACSubject , rac_signalForSelector 在下文中有详细介绍.

  1. 首先创建一个RedView的类继承于UIView

RedView.h

#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@interface RedView : UIView

// rac 实现代理
@property (nonatomic, strong)RACSubject *subject;

@end

NS_ASSUME_NONNULL_END

RedView.m

#import "RedView.h"

@implementation RedView

- (RACSubject *)subject{
    if(!_subject){
        _subject = [RACSubject subject];
    }
    return _subject;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.subject sendNext:@"红色视图"];
}

@end

控制器中代码:

#import "ViewController.h"
#import 
#import "RedView.h"

@interface ViewController ()

@property (nonatomic, strong)RedView *red;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self delegateTest];
}

- (void)delegateTest {
    
    self.red = [[RedView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    self.red.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.red];
    [self.red.subject subscribeNext:^(id  _Nullable x) {
        NSLog(@"代理: %@", x);
    }];
}
  • KVO

需要引入 #import 头文件
方式一:

- (void)RAC_KVOTest1 {
    
    self.kvoView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    self.kvoView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.kvoView];
    
    [self.kvoView rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:nil block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
        NSLog(@"监听到最新frame - %@", value);
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.kvoView.frame = CGRectMake(50, 50, 50, 50);
}

输出结果: 监听到最新frame - NSRect: {{50, 50}, {50, 50}}

方式二:

- (void)RAC_KVOTest2 {
    
    self.kvoView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    self.kvoView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.kvoView];
    
    [[self.kvoView rac_valuesForKeyPath:@"frame" observer:self] subscribeNext:^(id  _Nullable x) {
        // 刚开始运行, 就会先打印一遍原始值 -> 监听到最新frame - NSRect: {{100, 100}, {100, 100}}
        NSLog(@"监听到最新frame - %@", x);
        // 然后点击打印 -> 监听到最新frame - NSRect: {{50, 50}, {50, 50}}
    }];
}

方式三:

- (void)RAC_KVOTest3 {
    
    self.kvoView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    self.kvoView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.kvoView];
    
    // 使用RAC 封装的宏定义, 打印结果和方式2 一样
    [RACObserve(self.kvoView, frame) subscribeNext:^(id  _Nullable x) {
        NSLog(@"监听到最新frame - %@", x);
    }];
}
注意: 方式2、3中有注释提到, 在监听过程中会出现先打印一次原始数据值
  • rac_signalForSelector(监听方法)

- (void)rac_signalForSelectorTest {
    
    [[self rac_signalForSelector:@selector(touchesBegan:withEvent:)] subscribeNext:^(RACTuple * _Nullable x) {
        
        NSLog(@"监听屏幕点击方法: %@", x);
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

}
也可以用作代理的使用, 比如检测上面RedView 的点击事件
    [[self.red rac_signalForSelector:@selector(touchesBegan:withEvent:)] subscribeNext:^(RACTuple * _Nullable x) {
        
        NSLog(@"控制器知道RedView被点击了");
    }];
  • rac_signalForControlEvents(监听事件)

- (void)rac_signalForControlEventsTest {
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(200, 200, 100, 50)];
    button.backgroundColor = [UIColor blueColor];
    [self.view addSubview:button];
    
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        NSLog(@"按钮被点击了");
    }];
}
  • rac_textSignal(监听textfield输入)

- (void)rac_textSignalTest {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(200, 200, 100, 50)];
    textField.layer.borderColor = [UIColor redColor].CGColor;
    textField.layer.borderWidth = 1;
    textField.layer.cornerRadius = 5;
    textField.clipsToBounds = YES;
    [self.view addSubview:textField];
    [textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        // x:是最新文本数据
        NSLog(@"%@", x);
    }];
}
  • RAC 的宏

RAC(<#TARGET, ...#>)

RAC(对象,对象的属性) = (一个信号);
比如:RAC(button, enable) = (RACSignal) 按钮的enable 等于一个信号

.End

你可能感兴趣的:(RAC 中的通知、代理、KVO, 基本事件、方法的监听)