iOS开发 MVVM+RAC 的使用
好长一段时间没有敲简书了!
主要是因为一直在跑面试。
终于还是在上海入职了!
由于项目原因最终还是入了MVVM+RAC的坑
下面是正题。
Demo效果
使用MVVM+RAC请求网络数据

ReactiveCocoa简介
在iOS开发过程中,当某些事件响应的时候,需要处理某些业务逻辑,这些事件都用不同的方式来处理。
比如按钮的点击使用action,ScrollView滚动使用delegate,属性值改变使用KVO等系统提供的方式。
其实这些事件,都可以通过RAC处理
ReactiveCocoa为事件提供了很多处理方法,而且利用RAC处理事件很方便,可以把要处理的事情,和监听的事情的代码放在一起,这样非常方便我们管理,就不需要跳到对应的方法里。非常符合我们开发中高聚合,低耦合的思想。
基础的话我还是推荐这篇博文 讲的都挺细的
当然不爽的话可以试试这个视频版的,也是某培训机构流出的
Demo分析
本文使用的是豆瓣API(非官方)
Demo所要做的功能很简单: 从网络中请求数据,并加载到UI上。
MVVM中最重要也就是这个VM了,VM通常与RAC紧密结合在一起,主要用于事务数据的处理和信号间的传递。
Demo中主要使用了下面这些第三方库
pod 'SDWebImage'
pod 'Motis'
pod 'ReactiveCocoa', '2.5'
pod 'BlocksKit'
pod 'AFNetworking'
pod 'Masonry'
pod 'SVProgressHUD'
这里除了RAC 还有一个值得提一下
BlocksKit
众所周知Block已被广泛用于iOS编程。它们通常被用作可并发执行的逻辑单元的封装,或者作为事件触发的回调。Block比传统回调函数有2点优势:
- 允许在调用点上下文书写执行逻辑,不用分离函数
- Block可以使用local variables.
基于以上种种优点Cocoa Touch越发支持Block式编程,这点从UIView的各种动画效果可用Block实现就可以看出。而BlocksKit是对Cocoa Touch Block编程更进一步的支持,它简化了Block编程,发挥Block的相关优势,让更多UIKit类支持Block式编程。
代码
由于BlocksKit的使用,当我们写Delegate和Datasource时 就不用分离函数,整个逻辑都能凑在一起,比如这样定义一个collectionView:
- (void)initStyle {
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
collectionView.backgroundColor = [UIColor redColor];
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.showsVerticalScrollIndicator = NO;
collectionView.alwaysBounceVertical = YES;
[self.view addSubview:collectionView];
[collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.mas_topLayoutGuide);
make.left.right.equalTo(self.view);
make.bottom.equalTo(self.view.mas_bottom);
}];
self.collectionView = collectionView;
//注册cell
[self.collectionView registerClass:[MovieCollectionViewCell class] forCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier]];
//collectionView dataSouce
A2DynamicDelegate *dataSouce = self.collectionView.bk_dynamicDataSource;
//item个数
[dataSouce implementMethod:@selector(collectionView:numberOfItemsInSection:) withBlock:^NSInteger(UICollectionView *collectionView, NSInteger section) {
return self.listArray.count;
}];
//item配置
[dataSouce implementMethod:@selector(collectionView:cellForItemAtIndexPath:) withBlock:^UICollectionViewCell*(UICollectionView *collectionView,NSIndexPath *indexPath) {
id<MovieModelProtocol> cell = nil;
Class cellClass = [MovieCollectionViewCell class];
if (cellClass) {
cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MovieCollectionViewCell cellReuseIdentifier] forIndexPath:indexPath];
if ([cell respondsToSelector:@selector(renderWithModel:)]) {
[cell renderWithModel:self.listArray[indexPath.row]];
}
}
return (UICollectionViewCell *)cell;
}];
self.collectionView.dataSource = (id)dataSouce;
#define scaledCellValue(value) ( floorf(CGRectGetWidth(collectionView.frame) / 375 * (value)) )
//collectionView delegate
A2DynamicDelegate *delegate = self.collectionView.bk_dynamicDelegate;
//item Size
[delegate implementMethod:@selector(collectionView:layout:sizeForItemAtIndexPath:) withBlock:^CGSize(UICollectionView *collectionView,UICollectionViewLayout *layout,NSIndexPath *indexPath) {
return CGSizeMake(scaledCellValue(100), scaledCellValue(120));
}];
//内边距
[delegate implementMethod:@selector(collectionView:layout:insetForSectionAtIndex:) withBlock:^UIEdgeInsets(UICollectionView *collectionView ,UICollectionViewLayout *layout, NSInteger section) {
return UIEdgeInsetsMake(0, 15, 0, 15);
}];
self.collectionView.delegate = (id)delegate;
}
这就将所有有关collectionView的内容都包含在一起了,这样更符合逻辑。
我们让viewModel来处理网络请求,controller需要做的就是启动这个开关,并接受数据而已,所有的工作交给viewModel来处理
MovieViewModel.m
- (void)initViewModel {
@weakify(self);
self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
@strongify(self);
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
@strongify(self);
[self getDoubanList:^(NSArray<MovieModel *> *array) {
[subscriber sendNext:array];
[subscriber sendCompleted];
}];
return nil;
}];
}];
}
/**
网络请求
@param succeedBlock 成功回调
*/
- (void)getDoubanList:(void(^)(NSArray<MovieModel*> *array))succeedBlock {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSMutableArray *array = [NSMutableArray array];
MoviewModelList *base = [[MoviewModelList alloc] init];
[base mts_setValuesForKeysWithDictionary:responseObject];
//遍历数组取出 存入数组并回调出去
[base.subjects enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
MovieModel *model = [[MovieModel alloc] init];
[model mts_setValuesForKeysWithDictionary:obj];
[array addObject:model];
}];
if (succeedBlock) {
succeedBlock(array);
}
} failure:nil];
}
ViewController.m
- (void)bindViewModel {
@weakify(self);
//将命令执行后的数据交给controller
[self.viewModel.command.executionSignals.switchToLatest subscribeNext:^(NSArray<MovieModel *> *array) {
@strongify(self);
[SVProgressHUD showSuccessWithStatus:@"加载成功"];
self.listArray = array;
[self.collectionView reloadData];
[SVProgressHUD dismissWithDelay:1.5];
}];
//执行command
[self.viewModel.command execute:nil];
[SVProgressHUD showWithStatus:@"加载中..."];
}
Demo地址
iOS开发 MVVM+RAC 的使用的更多相关文章
- iOS开发--Swift RAC响应式编程初探
时间不是很充足, 先少说点, RAC的好处是响应式编程, 不需要自己去设置代理委托, target, 而是主要以信息流(signal), block为主, 看到这里激动吧, 它可以帮你监听你的事件, ...
- iOS开发--Swift RAC响应式编程
时间不是很充足, 先少说点, RAC的好处是响应式编程, 不需要自己去设置代理委托, target, 而是主要以信息流(signal), block为主, 看到这里激动吧, 它可以帮你监听你的事件, ...
- iOS开发之浅谈MVVM的架构设计与团队协作
今天写这篇博客是想达到抛砖引玉的作用,想与大家交流一下思想,相互学习,博文中有不足之处还望大家批评指正.本篇博客的内容沿袭以往博客的风格,也是以干货为主,偶尔扯扯咸蛋(哈哈~不好好工作又开始发表博客啦 ...
- [HMLY]7.iOS MVVM+RAC 从框架到实战
1.MVVM浅析 MVC是构建iOS App的标准模式,是苹果推荐的一个用来组织代码的权威范式,市面上大部分App都是这样构建的,具体组织模式不细说,iOS入门者都比较了解(虽然不一定能完全去遵守), ...
- iOS开发项目之MVC与MVVM
MVC MVC,Model-View-Controller,我们从这个古老而经典的设计模式入手.采用 MVC 这个架构的最大的优点在于其概念简单,易于理解,几乎任何一个程序员都会有所了解,几乎每一所计 ...
- iOS MVVM+RAC 从基础到demo
一.关于经典模式MVC的简介 MVC是构建iOS App的标准模式,是苹果推荐的一个用来组织代码的权威范式,市面上大部分App都是这样构建的,具体组建模式不细说,iOS入门者都比较了解(虽然不一定能完 ...
- iOS:iOS开发非常全的三方库、插件等等
iOS开发非常全的三方库.插件等等 github排名:https://github.com/trending, github搜索:https://github.com/search. 此文章转自git ...
- iOS开发--iOS及Mac开源项目和学习资料
文/零距离仰望星空(简书作者)原文链接:http://www.jianshu.com/p/f6cdbc8192ba著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 原文出处:codecl ...
- iOS开发--完整项目
完整项目 Phonetic Swift 写的一个 iOS 版的 Phonetic Contacts,功能很多,其中昵称功能非常实用,已在 GitHub 开源并上架 App Store v2ex – v ...
随机推荐
- python基础之数据类型/字符串/元组/列表/字典
Python 数据类型 数字类型: int整型,long 长整型(在python3.0里不区分整型和长整型).float浮点型:complex复数(python中存在小数字池:-5--257):布尔值 ...
- mac os 安装PIP 及异常“”Can't install python module: PyCharm Error: “byte-compiling is disabled, skipping”“”的解决方案
For all who have the same problem, it took me a while to find the solution in a new installation of ...
- scrapy配置
scrapy配置 增加并发 并发是指同时处理的request的数量.其有全局限制和局部(每个网站)的限制. Scrapy默认的全局并发限制对同时爬取大量网站的情况并不适用,因此您需要增加这个值. 增加 ...
- css透明度的设置
Css代码 .transparent_class { filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: ...
- 玩转spring boot——websocket
前言 QQ这类即时通讯工具多数是以桌面应用的方式存在.在没有websocket出现之前,如果开发一个网页版的即时通讯应用,则需要定时刷新页面或定时调用ajax请求,这无疑会加大服务器的负载和增加了客户 ...
- JAVAEE学习路线分享
今天把我的教学经验分享给大家.适合大多数人的学习路线.注:目前作者已经转行做java培训. 首先是培养兴趣.先开始学习HTML知识.也就是做网页,从这里开始比较简单,就是几个标签单词需要记住. 接着开 ...
- 【LeetCode】89. Gray Code
题目: The gray code is a binary numeral system where two successive values differ in only one bit. Giv ...
- 【Android Developers Training】 93. 创建一个空验证器
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 理解oauth2.0【转载】
原文出处: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html OAuth是一个关于授权(authorization)的开放网络标准,在全世界得 ...
- Javascript 类继承
Js继承 JavaScript并不是真正面向对象的语言,是基于对象的,没有类的概念. 要想实现继承,可以用js的原型prototype机制或者用apply和call方法去实现 /** 声明一个基础父类 ...