参考:http://www.ruanyifeng.com/blog/2015/02/mvcmvp_mvvm.html
一、MVVM 分为3个模块 1.View 2.ViewModel 3.Model
关系为:
注意:View和ViewModel之间是双向绑定的,即View的变动将自动反映在ViewModel上,ViewModel的变动自动反映在View上。
二、MVVM出现的原因:
传统MVC模式中Controller中做了太多的数据加工的事情,随着软件规模的增长,越来越不好维护。越来越不好测试。所以MVVM把数据加工的任务从Controller中解放了出来。使得Controller只需专注于数据调配的工作。ViewModel则去负责数据加工并通过通知机制让View响应ViewModel的改变。(注意这里的View指的是ViewController)
三、View 和 ViewModel的交互
重点讲解:View和ViewModel的交互(核心)
首先要明确的一点是ViewModel的职能:网络请求、网络请求后数据的处理以及数据模型的转换、数据库操作、页面跳转逻辑、以及相关的数据处理等。
示例:
1.定义一个ViewModel的父类。用来处理所以ViewModel公共的部分
#import <Foundation/Foundation.h>
@interface ViewModelClass : NSObject
@property (strong, nonatomic) ReturnValueBlock returnBlock;
@property (strong, nonatomic) ErrorCodeBlock errorBlock;
@property (strong, nonatomic) FailureBlock failureBlock;
// 传入交互的Block块
-(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock
WithErrorBlock: (ErrorCodeBlock) errorBlock
WithFailureBlock: (FailureBlock) failureBlock;
@end
#import "ViewModelClass.h"
@implementation ViewModelClass
#pragma 接收穿过来的block
-(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock
WithErrorBlock: (ErrorCodeBlock) errorBlock
WithFailureBlock: (FailureBlock) failureBlock
{
_returnBlock = returnBlock;
_errorBlock = errorBlock;
_failureBlock = failureBlock;
}
@end
2.定义一个WeiboViewModel的子类
#import "ViewModelClass.h"
#import "PublicModel.h"
@interface WeiboViewModel : ViewModelClass
//获取微博列表
-(void) fetchPublicWeiBo;
//跳转到微博详情页
-(void) weiboDetailWithPublicModel: (PublicModel *) publicModel WithViewController: (UIViewController *)superController;
@end
#import "WeiboViewModel.h"
#import "DetailViewController.h"
@implementation WeiboViewModel
//获取公共微博
-(void) fetchPublicWeiBo
{
NSDictionary *parameter = @{TOKEN: ACCESSTOKEN,
COUNT: @"100"
};
[NetRequestClass NetRequestGETWithRequestURL:REQUESTPUBLICURL WithParameter:parameter WithReturnValeuBlock:^(id returnValue) {
[self fetchValueSuccessWithDic:returnValue];
} WithErrorCodeBlock:^(id errorCode) {
DDLog(@"%@", errorCode);
[self errorCodeWithDic:errorCode];
} WithFailureBlock:^{
[self netFailure];
DDLog(@"网络异常");
}];
}
#pragma 获取到正确的数据,对正确的数据进行处理
-(void)fetchValueSuccessWithDic: (NSDictionary *) returnValue
{
//对从后台获取的数据进行处理,然后传给ViewController层进行显示
NSArray *statuses = returnValue[STATUSES];
NSLog(@"returnValue====%@",returnValue);
NSMutableArray *publicModelArray = [[NSMutableArray alloc] initWithCapacity:statuses.count];
for (int i = 0; i < statuses.count; i ++) {
PublicModel *publicModel = [[PublicModel alloc] init];
//设置时间
NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc]init];
iosDateFormater.dateFormat=@"EEE MMM d HH:mm:ss Z yyyy";
//必须设置,否则无法解析
iosDateFormater.locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
NSDate *date=[iosDateFormater dateFromString:statuses[i][CREATETIME]];
//目的格式
NSDateFormatter *resultFormatter=[[NSDateFormatter alloc]init];
[resultFormatter setDateFormat:@"MM月dd日 HH:mm"];
publicModel.date = [resultFormatter stringFromDate:date];
publicModel.userName = statuses[i][USER][USERNAME];
publicModel.text = statuses[i][WEIBOTEXT];
publicModel.imageUrl = [NSURL URLWithString:statuses[i][USER][HEADIMAGEURL]];
publicModel.userId = statuses[i][USER][UID];
publicModel.weiboId = statuses[i][WEIBOID];
[publicModelArray addObject:publicModel];
}
self.returnBlock(publicModelArray);
}
#pragma 对ErrorCode进行处理
-(void) errorCodeWithDic: (NSDictionary *) errorDic
{
self.errorBlock(errorDic);
}
#pragma 对网路异常进行处理
-(void) netFailure
{
self.failureBlock();
}
#pragma 跳转到详情页面,如需网路请求的,可在此方法中添加相应的网络请求
-(void) weiboDetailWithPublicModel: (PublicModel *) publicModel WithViewController:(UIViewController *)superController
{
DDLog(@"%@,%@,%@",publicModel.userId,publicModel.weiboId,publicModel.text);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
DetailViewController *detailController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
detailController.publicModel = publicModel;
[superController.navigationController pushViewController:detailController animated:YES];
}
@end
3.实现 PublicTableViewController
#import "PublicTableViewController.h"
#import "WeiboViewModel.h"
#import "PublicCell.h"
@interface PublicTableViewController ()
@property (strong, nonatomic) NSArray *publicModelArray;
@end
@implementation PublicTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
WeiboViewModel *publicViewModel = [[WeiboViewModel alloc] init];
//初始化block
[publicViewModel setBlockWithReturnBlock:^(id returnValue) {
[SVProgressHUD dismiss];
_publicModelArray = returnValue;
[self.tableView reloadData];
DDLog(@"%@",_publicModelArray);
} WithErrorBlock:^(id errorCode) {
[SVProgressHUD dismiss];
} WithFailureBlock:^{
[SVProgressHUD dismiss];
}];
[publicViewModel fetchPublicWeiBo];
[SVProgressHUD showWithStatus:@"正在获取用户信息" maskType:SVProgressHUDMaskTypeBlack];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _publicModelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PublicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PublicCell" forIndexPath:indexPath];
[cell setValueWithDic:_publicModelArray[indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
WeiboViewModel *publicViewModel = [[WeiboViewModel alloc] init];
[publicViewModel weiboDetailWithPublicModel:_publicModelArray[indexPath.row] WithViewController:self];
}
@end
以上实例虽然不全但是可以加深对于MVVM的理解。仅仅入门而已。
目前ReactiveCocoa+MVVM是比较流行的,有时间的同学可以深入研究。