天天看点

iOS开发之ReactiveCocoa框架(RAC)第一篇

简介:ReactiveCocoa为事件提供了很多处理方法,而且利用RAC处理事件很方便,可以把要处理的事情和监听的事情的代码放在一起,这样非常方便我们管理,就不需要跳到对应的方法里。那我们该如何灵活运用ReactiveCocoa呢?

系列学习总结:

-传统代码调用向RAC信号量的转变:信号量对于RAC函数编程的核心,对于OC的所有设计模式都提供了转换途径,除了涉及到的普通调用,委托协议,KVO等等以外,还有通知中心,线程的信号量转换方式。另外UIKit框架中也有很多控件对RAC框架进行了扩展

-3个由简到难的实际操作案例

-信号量和队列的特性,以及一系列的高级操作函数

RAC初识-设计模式+RAC信号量的统一

Cocoapods引入ReactiveCocoa

Podfile文件

platform :ios, "8.0"
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!

target :'ReactiveCocoaDemo' do
pod 'ReactiveCocoa', '~> 2.5'
end
           

注:如何安装使用CocoaPods,请参考另一篇文章:

http://blog.csdn.net/wtdask/article/details/74645581

.h文件

#import "ViewController.h"

@import ReactiveCocoa;
@interface ViewController()
{

}
- (void)viewDidLoad {
    [super viewDidLoad];
    /*
     ReactiveCocoa框架方式
     */
    //信号量
    RACSignal * viewDidAppearSiganl =[self rac_signalForSelector:@selector(viewDidAppear:)];

    [viewDidAppearSiganl subscribeNext:^(id x) {
        //会在每次viewDidAppear调用的时候,执行
        NSLog(@"打印日志:viewDidAppearSiganl-%s",__func__);
        NSLog(@"打印日志:参数-%@",x);
    }];

    [viewDidAppearSiganl subscribeError:^(NSError *error) {
        //订阅错误

    }];

    [viewDidAppearSiganl subscribeCompleted:^{

        //订阅完成状态
    }];

    UIButton * button =[UIButton buttonWithType:UIButtonTypeSystem];
    [button setRac_command:[[RACCommand alloc] initWithEnabled:nil signalBlock:^RACSignal *(id input) {

        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            NSLog(@"Clicked");

//            测试异步操作
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                [subscriber sendNext:[[NSDate date] description]];//返回给当前的时间给订阅者
                [subscriber sendCompleted];//调用sendCompleted来结束这次按键的操作
            });
            return [RACDisposable disposableWithBlock:^{


            }];
        }];
    }]];
    [[[button rac_command] executionSignals] subscribeNext:^(id x) {

        [x subscribeNext:^(id x) {

            NSLog(@"%@",x);
        }];
    }];

    [button setTitle:@"点我" forState:UIControlStateNormal];
    [button setBounds:CGRectMake(, , , )];
    [self.view addSubview:button];
    [button setCenter:CGPointMake(self.view.frame.size.width/, self.view.frame.size.height/)];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self setNeedsStatusBarAppearanceUpdate];
    NSLog(@"打印日志:%s",__func__);
}
           
iOS开发之ReactiveCocoa框架(RAC)第一篇