ReactiveCocoa解析之常用方法

代替代理:

  • - (RACSignal *)rac_signalForSelector:(SEL)selector
范例:
//A控制器
[[_redView rac_signalForSelector:@selector(btnClick:)] subscribeNext:^(id x) {
        NSLog(@"控制器知道按钮被点击");
}];
//A控制器引用的B控制器(_redView)
- (IBAction)btnClick:(id)sender
{
    NSLog(@"按钮被点击");
}
  • 之前介绍的 RACSubject

代替KVO

  • - (RACDisposable *)rac_observeKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options observer:(__weak NSObject *)weakObserver block:(void (^)(id, NSDictionary *, BOOL, BOOL))block
范例:
//监听redViewframe的改变
[_redView rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:nil block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
        //修改frame的代码
    }];
  • - (RACSignal *)rac_valuesForKeyPath:(NSString *)keyPath observer:(__weak NSObject *)observer
范例:
    [[_redView rac_valuesForKeyPath:@"frame" observer:nil] subscribeNext:^(id x) {
      // x:修改的值
        NSLog(@"%@",x);
    }];

监听事件

  • - (RACSignal *)rac_signalForControlEvents:(UIControlEvents)controlEvents
范例:
[[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
       NSLog(@"按钮点击了");
}];

代替通知

  • - (RACSignal *)rac_addObserverForName:(NSString *)notificationName object:(id)object
范例:
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(id x) {
        NSLog(@"%@",x);
}];

处理多个请求,都返回结果的时候,统一做处理.

RACSignal *request1 = [RACSignal createSignal:^RACDisposable *(id subscriber) {

        // 发送请求1
        [subscriber sendNext:@"发送请求1"];
        return nil;
    }];

    RACSignal *request2 = [RACSignal createSignal:^RACDisposable *(id subscriber) {
        // 发送请求2
        [subscriber sendNext:@"发送请求2"];
        return nil;
    }];

    // 使用注意:几个信号,参数一的方法就几个参数,每个参数对应信号发出的数据。
    [self rac_liftSelector:@selector(updateUIWithR1:r2:) withSignalsFromArray:@[request1,request2]];
// 更新UI
- (void)updateUIWithR1:(id)data r2:(id)data1
{
    NSLog(@"更新UI%@  %@",data,data1);
}

你可能感兴趣的:(ReactiveCocoa解析之常用方法)