RAC(ReactiveCocoa)使用方法(一)

RAC(ReactiveCocoa)使用方法(二)

上篇文章:RAC(ReactiveCocoa)使用方法(一)

中主要介绍了一些RAC中常见类的用法,这篇文章主要总结日常开发中结合一些UI控件的用法。

RAC给常见的很多UI类拓展了用法,使得开发变得越来越简单,减少了很多不必要的代理和Target代码,RAC内部已经处理好了这些事件。

网络请求

贴上核心代码,具体代码见Github;

//
// ViewModel.m
//
//
// Created by soliloquy on 2017/11/28.
// //豆瓣电影API
#define url @"https://api.douban.com/v2/movie/in_theaters?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&start=0&count=100&client=&udid=" #import "ViewModel.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "Model.h" @implementation ViewModel
- (instancetype)init
{
self = [super init];
if (self) {
__weak typeof (self)weakSelf = self;
self.command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { [weakSelf fetchData:^(NSArray *arr) {
[subscriber sendNext:arr];
[subscriber sendCompleted];
} failure:^(NSError *error) {
[subscriber sendError:error];
}]; return nil;
}];
}]; }
return self;
} - (void)fetchData:(void(^)(NSArray *arr))successBlock failure:(void(^)(NSError *error))failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSArray *arr = [Model mj_objectArrayWithKeyValuesArray:responseObject[@"subjects"]];
/** 方法一:block回调出去
if (self.dataSourceBlock) {
self.dataSourceBlock(arr);
}
*/
/**
方法二 : ReactiveCocoa
*/ if (successBlock) {
successBlock(arr);
} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) {
failure(error);
} }];
} @end
- (void)viewDidLoad {
[super viewDidLoad]; [self bindViewModel];
} - (void)bindViewModel {
/** RAC */
@weakify(self)
[self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(NSArray *dataSource) {
@strongify(self);
self.dataSource = dataSource; NSLog(@"%@",dataSource);
}]; // 返回错误
[self.viewModel.command.errors subscribeNext:^(NSError *_Nullable x) {
NSLog(@"-- error : %@", x.description);
}]; //执行command
[self.viewModel.command execute:nil];
}

代理

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题" message:@"123456" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"other", nil];
[[self rac_signalForSelector:@selector(alertView:clickedButtonAtIndex:) fromProtocol:@protocol(UIAlertViewDelegate)] subscribeNext:^(RACTuple *tuple) {
NSLog(@"%@",tuple.first);
NSLog(@"%@",tuple.second);
NSLog(@"%@",tuple.third);
}];
[alertView show];

通知

  • 发送通知
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"notiName" object:dataArray];
  • 接收通知
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"notiName" object:nil] subscribeNext:^(NSNotification *notification) {
NSLog(@"%@", notification.name);
NSLog(@"%@", notification.object);
}];

KVO

    UIScrollView *scrolView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
scrolView.contentSize = CGSizeMake(200, 800);
scrolView.backgroundColor = [UIColor redColor];
[self.view addSubview:scrolView];
[RACObserve(scrolView, contentOffset) subscribeNext:^(id x) {
NSLog(@"contentOffset: %@",x);
}];

Target-Action

  • UIButton
[[self.button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
NSLog(@"x:%@", x);
}];
  • UITextField
[self.tf.rac_textSignal subscribeNext:^(id x) {
NSLog(@"x:%@", x);
self.label.text = x;
}];
[[self.tf.rac_textSignal map:^id(id value) {
return [UIColor redColor];
}] subscribeNext:^(id x) {
// NSLog(@"x:%@", x);
}];
  • UIView
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
[tap.rac_gestureSignal subscribeNext:^(id x) {
NSLog(@"x:%@", x);
self.redView.backgroundColor = [UIColor yellowColor];
}];
[self.redView addGestureRecognizer: tap];

详情见github.

RAC(ReactiveCocoa)使用方法(二)的更多相关文章

  1. RAC(ReactiveCocoa)使用方法(一)

    RAC(ReactiveCocoa)使用方法(一) RAC(ReactiveCocoa)使用方法(二) 什么是RAC? 最近回顾了一下ReactiveCocoa的方法,也看了一些人的文章,现写篇文章总 ...

  2. RAC(ReactiveCocoa)介绍(一)

    最近在学习RAC,之前在iOS工作中,类之间的传值,无非是block.delegate代理.KVO和Notification等这几种方法.在RAC中,同样具备替代block.delegate代理.KV ...

  3. AIX下RAC搭建 Oracle10G(二)主机配置

    AIX下RAC搭建系列 AIX下RAC搭建 Oracle10G(二)主机配置 环境 节点 节点1 节点2 小机型号 IBM P-series 630 IBM P-series 630 主机名 AIX2 ...

  4. Android抓包方法(二)之Tcpdump命令+Wireshark

    Android抓包方法(二) 之Tcpdump命令+Wireshark 前言 做前端测试,基本要求会抓包,会分析请求数据包,查看接口是否调用正确,数据返回是否正确,问题产生是定位根本原因等.学会抓包分 ...

  5. Java 简单实用方法二

    整理以前的笔记,在学习Java时候,经常会用到一些方法.虽然简单但是经常使用.因此做成笔记,方便以后查阅 这篇博文先说明构造和使用这些方法. 1,判断String类型数据是否包含中文 可以通过正则表达 ...

  6. SSH框架的多表查询(方法二)增删查改

     必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html  一:在前一个方法(http://www.cnblogs.com/zhu520/p ...

  7. Microsoft Edge浏览器下载文件乱码修复方法(二)

    之前有写过"Microsoft Edge浏览器下载文件乱码修复方法",发现很多情况下下载文件乱码问题还是存在,这里对之前内容做简单补充,希望可以帮到大家. 方法二: 默认如果提示下 ...

  8. mybatis由浅入深day02_2一对一查询_2.3方法二:resultMap_resultType和resultMap实现一对一查询小结

    2.3 方法二:resultMap 使用resultMap,定义专门的resultMap用于映射一对一查询结果. 2.3.1 sql语句 同resultType实现的sql SELECT orders ...

  9. Selenium应用代码(常见封装的方法二)

    滚动窗口: //将滚动条滚到适合的位置 , 方法一 public static void setScroll(WebDriver driver,int height){ try { // String ...

随机推荐

  1. C# 基础之类型(一)

    一.类型 类型总共分为两种,一种是值类型(Value Type),如枚举.结构:另一种是引用类型(Reference Type),如类.接口.委托等. 值类型 1,值类型通常分配在线程的堆栈上 2,作 ...

  2. ROS Indigo在ubuntu1404上的安装方法

    安装配置方法参照  http://wiki.ros.org/indigo/Installation/Ubuntu 以下操作需要保证虚拟机能够正常连接网络. 1.更换源镜像: 将源设置为国内源,我选择的 ...

  3. UVa816,Ordering Tasks,WA

    #include <iostream> #include <cstdio> #include <string> #include <cstring> # ...

  4. RabbitMQ 笔记-基本概念

    ConnectionFactory.Connection.Channel ConnectionFactory.Connection.Channel,这三个都是RabbitMQ对外提供的API中最基本的 ...

  5. bootstrap 鼠标悬停显示

    1. <button type="button" rel="drevil" data-content="报名截止时间:'+time+'" ...

  6. LeetCode 455. Assign Cookies (分发曲奇饼干)

    Assume you are an awesome parent and want to give your children some cookies. But, you should give e ...

  7. MQTT——连接报文

    学习MQTT协议.如果只是看了相关文档就认为可以了.那是一个错误的观念.笔者为了能更好的去理解MQTT协议.看了不少相关的开源Broker的项目.可惜这些项目一般都是不完全的.不过从这些项目中笔者至少 ...

  8. CSS选择器汇总

    id选择器 #id 类选择器 .class 标签选择器 div, h1, p 相邻选择器 h1 + p 子选择器 ul > li 后代选择器 li a 通配符选择器 * 属性选择器 a[rel= ...

  9. ssh免密码记录

    主机器A通过ssh连多台从机器(b1,b2,b3). 1.使用root用户操作,避免权限问题. 2.在主从机器中安装ssh,命令: ssh-keygen –t rsa 然后都回车,生成的文件在/roo ...

  10. 2301: [HAOI2011]Problem b ( 分块+莫比乌斯反演+容斥)

    2301: [HAOI2011]Problem b Time Limit: 50 Sec  Memory Limit: 256 MBSubmit: 6015  Solved: 2741[Submit] ...