GitHub地址:ReactiveCocoa
一、响应式编程就是实时响应某个事件
// 创建信号 RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id _Nonnull subscriber) { NSLog(@"Hello"); // 发送信号 [subscriber sendNext:@"This is RAC"]; return nil; }]; // 订阅信号 [signal subscribeNext:^(id _Nullable x) { NSLog(@"%@",x); }];
二、RAC很强大,一行代码搞定以前的事件监听
举几个实际使用案例
1. TargetAction转Block
①UITextField(实时监听输入框内容)
[[self.textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) { NSLog(@"%@", x); }];
②UIButton(Button点击事件)
[[self.button rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) { NSLog(@"%@",x); }];
2. 通知转Block
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) { NSLog(@"%@",x); }];
三、注意事项:
RAC使用@weakify(self);和@strongify(self);来避免block循环引用
@weakify(self); [[self.textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) { @strongify(self); self.textField.text = @"Hello"; }];