RAC 小记(初学者入门基础一)

RAC(ReactiveCocoa)就是平常所说的函数式响应式编程,最基本的使用就是对事件的监听

配置RAC环境:这里声明一点,最新版本已经支持swift,但是OC的程序安装最新的RAC可能跑步起来,所以大家最好是用2.5.0以下的版本

使用cocoa pods进行集成:

推荐大家在Podfile文件中使用:platform:ios,'8.0'pod'ReactiveCocoa','~>2.1.8'

基本使用:

1.给按钮添加监听事件

[[self.myButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {

//x代表的是当前这个按钮的属性信息

NSLog(@"%@",self.myButton.currentTitle);//这里是处理点击按钮之后用户要做的事情

}];

2.给视图添加手势

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init];

[[gesture rac_gestureSignal] subscribeNext:^(id x) {

self.myView.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0];

}];

[self.myView addGestureRecognizer:gesture];

3.写代理,但是只能实现返回值为void的代理方法


self.alertView = [[UIAlertView alloc] initWithTitle:@"测试RAC" message:@"我是RAC" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

[[self rac_signalForSelector:@selector(alertView:clickedButtonAtIndex:) fromProtocol:@protocol(UIAlertViewDelegate)] subscribeNext:^(RACTuple *tuple) {//tuple是一个集合,tuple.second指的是ButtonAtIndex中button的序号,如果点击的是取消就是代表的0,如果是点击的是确定就是代表的是1

NSLog(@"%@",tuple.second);

}];

[self.alertView show];


也可简化代理方法

[[self.alertView rac_buttonClickedSignal] subscribeNext:^(id x) {

NSLog(@"%@",x);//这里的x代表的就是点击的哪个按钮的序号

}];

4.KVO的使用

self.inputStr = @"我是输入";

[RACObserve(self,inputStr)

subscribeNext:^(NSString *x){

NSLog(@"%@",x);//发送一个请求

}];

5.通知的实现

RAC中的通知不需要remove observer,因为在rac_add方法中他已经写了remove。

注册接收通知:

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"arrayDataPost" object:nil] subscribeNext:^(NSNotification *notification) {

NSLog(@"%@",notification);

}];

发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"arrayDataPost" object:dict];

你可能感兴趣的:(RAC 小记(初学者入门基础一))