RAC用法笔记(一)

2018-05-14  本文已影响28人  handsome5

RAC

RAC 全称ReactiveCocoa, 一个超级重量的第三方框架,接管了苹果的所有事件机制,RAC主要是监听事件,并能立即作出响应,即响应式编程.

RAC.png
RAC信号三部曲
  • 1)创建信号
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { NSLog(@"test Project"); return nil; }];
  • 2)订阅信号
    [signal subscribeNext:^(id _Nullable x) { //x 信号的内容 NSLog(@"%@",x); }];
  • 3)发送信号
    [subscriber sendNext:@"this is test"];
    注意 [subscriber sendNext:@"this is test"];放在创建信号里,在创建信号里有个block参数subscriber(订阅者),接受到订阅信号源时,才能发送信号,订阅信号也能通过block接受发送信号的内容.
  • 合并写法
    [[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) { //发送信号 [subscriber sendNext:@"This is RAC"]; return nil; }] subscribeNext:^(id _Nullable x) { NSLog(@"x"); }] ;

RAC的使用

 [[self.btn rac_signalForControlEvents:(UIControlEventTouchUpInside)]subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"%@",x);
    }];
   @weakify(self);
    [[self.testTextFileld rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@",x);
    @strongify(self);
        self.testTextFileld.text = @"Hello";
    }];
[[RACSignal combineLatest:@[nameTextField.rac_textSignal, pwdTextField.rac_textSignal] reduce:^id _Nullable(NSString * name, NSString * pwd){
       NSLog(@"%@ ,%@", name,pwd);
       return @(name.length > 0 && pwd.length > 0);
       return nil;
   }] subscribeNext:^(id  _Nullable x) {
       NSLog(@"%@",x);
       
       _demoButton.enabled = [x boolValue];
   }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"%@",x);
    }];
@property(noatomic,assign) int age; 
[[self rac_valueForKeyPath:@"age" observer:nil] subscribeNext:^(id x ){ NSLog(@"%@",x); }]; 
//模拟一个事件 触摸屏幕 就让age自增
 -(void)touchesBegin:(NSSet<UITouch*>*)touches WithEvent:(UIEvent*)event{   
   age++; 
}
如:监听当前视图控制器中心点的变化
[RACObserver (self.view,center) subscribeNext:^(id x){

}];
RACTuple*tuple = RACTuplePack(@1,@3); NSLog(@"%@",tuple); 
//快速解析元组
 RACTupleUnPack(NSNumber*num1,NSNumber*num2) = tuple; 
//宏的参数表示你需要把这个元组解析成什么类型的数据

....

RAC的好处太多,一旦使用之后就很难丢弃了,但是RAC里面还是有很多坑的,RAC最大的坑就是循环引用,RAC采用 @weakify @strongify 两个宏来处理循环引用

  // UITextFeild 监听的 preprocess
    @autoreleasepool {} __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);;

  // UITextFeild 监听的 preprocess
 __attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_;
   @weakify(self);
    [[self.testTextFileld rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@",x);
    @strongify(self);
        self.testTextFileld.text = @"Hello";
    }];
上面code循环引用在哪里?
__weak typeof(self)weakSelf = self;和 @weakify 有什么区别呢?

案例地址

上一篇 下一篇

猜你喜欢

热点阅读