下载代码请点击
Controller要完全知道Model的内容,不受限制地访问Model;相反,Model 通过 Notification 和 KVO 机制与 Controller 间接通信。
Controller也能与View通信,如通过outlet;相反View也能与Controller通信,但是View是通用的,所以它不能对Controller的类知道得太多,只能以一种“盲”的方式去通信,如关联一个action、委托(delegate)协议。
Model 和 View 永远不能相互通信,只能通过 Controller 传递。
这个模式的核心是ViewModel,它是一种特殊的model类型,用于表示程序的UI状态。它包含描述每个UI控件的状态的属性。例如,文本输入域的当前文本,或者一个特定按钮是否可用。它同样暴露了视图可以执行哪些行为,如按钮点击或手势。可以将ViewModel看作是视图的模型(model-of-the-view)。
实际上ViewModel暴露属性来表示UI状态,它同样暴露命令来表示UI操作(通常是方法)。ViewModel负责管理基于用户交互的UI状态的改变。
MVVM模式中的三部分比MVC更加简洁,下面是一些严格的限制:
MVVM具有以下两个明显的优势:
View引用了ViewModel,但ViewModel没有引用View,那ViewModel如何更新视图呢?MVVM模式依赖于数据绑定,它是一个框架级别的特性,用于自动连接对象属性和UI控件。
pod 'ReactiveObjC'
pod 'Masonry', '~>1.1.0'
pod 'AFNetworking', '~> 3.1.0'
pod 'MBProgressHUD', '~> 1.1.0'
pod 'SDWebImage', '~> 4.3.2'
pod 'LinqToObjectiveC', '~> 2.1.0'
pod 'FMDB', '~> 2.7.2'
pod 'MJRefresh', '~> 3.1.15.3'
//创建界面元素
UITextField *userNameTextField = [[UITextField alloc] init];
userNameTextField.borderStyle = UITextBorderStyleRoundedRect;
userNameTextField.placeholder = @"请输入用户名…";
[userNameTextField becomeFirstResponder];
[self.view addSubview:userNameTextField];
self.userNameT = userNameTextField;
UITextField *passwordTextField = [[UITextField alloc] init];
passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
passwordTextField.placeholder = @"请输入密码…";
passwordTextField.secureTextEntry = YES;
[self.view addSubview:passwordTextField];
self.passWordT = passwordTextField;
UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
[loginButton setTitle:@"登录" forState:UIControlStateNormal];
[self.view addSubview:loginButton];
self.loginB = loginButton;
//布局界面元素
[passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_left).offset(10);
make.centerY.equalTo(self.view.mas_centerY);
make.right.equalTo(self.view.mas_right).offset(-10);
make.height.equalTo(@30);
}];
[userNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_left).offset(10);
make.bottom.equalTo(passwordTextField.mas_top).offset(-10);
make.right.equalTo(self.view.mas_right).offset(-10);
make.height.equalTo(@(30));
}];
[loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(passwordTextField.mas_left).offset(44);
make.top.equalTo(passwordTextField.mas_bottom).offset(10);
make.right.equalTo(passwordTextField.mas_right).offset(-44);
make.height.equalTo(@(30));
}];
#import
@interface UserModel : NSObject
@property (copy, nonatomic) NSString *username;
@property (copy, nonatomic) NSString *password;
@property (assign, nonatomic, getter=isLogined) BOOL logined;
+ (instancetype)userModelWithUsername:(NSString *)username password:(NSString *)password logined:(BOOL)logined;
- (instancetype)initWithUsername:(NSString *)username password:(NSString *)password logined:(BOOL)logined;
@end
@interface Result : NSObject
@property (assign, nonatomic) BOOL success;
@property (copy, nonatomic) NSString *message;
@property (strong, nonatomic) id responseObject;
+ (instancetype)resultWithSuccess:(BOOL)success message:(NSString *)message responseObject:(id)responseObject;
- (instancetype)initWithSuccess:(BOOL)success message:(NSString *)message responseObject:(id)responseObject;
@end
@interface Services : NSObject
- (RACSignal *)loginSignal:(NSString *)userName passWord:(NSString *)passWord;
- (RACSignal *)logoutSignal:(NSString *)userName passWord:(NSString *)passWord;
- (RACSignal *)searchSignal:(NSString *)searchText;
- (RACSignal *)allFriendsSignal;
- (RACSignal *)friendSignalWithPage:(NSInteger)page andCount:(NSInteger)count;
- (RACSignal *)searchSignalWithContent:(NSString *)content page:(NSInteger)page andCount:(NSInteger)count;
@end
@interface User : NSObject
@property (strong, nonatomic, readonly) Services *services;
@property (strong, nonatomic) UserModel *userModel;
@property (assign, nonatomic, readonly, getter=isValidOfUsername) BOOL validOfUsername;
@property (assign, nonatomic, readonly, getter=isValidOfPassword) BOOL validOfPassword;
+ (instancetype)userWithServices:(Services *)services userModel:(UserModel *)model;
- (instancetype)initWithServices:(Services *)services userModel:(UserModel *)model;
- (RACSignal *)loginSignal;
- (RACSignal *)logoutSignal;
@end
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) RACCommand *loginCommand;
+ (instancetype)loginViewModelWithUser:(User *)user;
- (instancetype)initWithUser:(User *)user;
前面说了ViewModel,它是一种特殊的model类型,用于表示程序的UI状态。它包含描述每个UI控件的状态的属性。但是我还是把用户名和密码放到数据层,方便传递,因为ViewModel拥有Model,所以并不影响他表示的UI状态、包含描述每个UI控件的状态的属性。
RACCommand 并不表示数据流,它只是一个继承自 NSObject 的类,但是它却可以用来创建和订阅用于响应某些事件的信号。它本身并不是一个 RACStream 或者 RACSignal 的子类,而是一个用于管理 RACSignal 的创建与订阅的类。RACCommand的基本属性:
+ (instancetype)loginViewModelWithUser:(User *)user {
return [[self alloc] initWithUser:user];
}
- (instancetype)initWithUser:(User *)user {
if (self = [super init]) {
self.user = user;
//创建有效的用户名密码信号
@weakify(self);
RACSignal *validUS = [[RACObserve(self.user.userModel, username) map:^id _Nullable(id _Nullable value) {
@strongify(self);
return @(self.user.isValidOfUsername);
}] distinctUntilChanged];
RACSignal *validPS = [[RACObserve(self.user.userModel, password) map:^id _Nullable(id _Nullable value) {
@strongify(self);
return @(self.user.isValidOfPassword);
}] distinctUntilChanged];
//合并有效的用户名密码信号作为控制登录按钮可用的信号
RACSignal *validLS = [RACSignal combineLatest:@[validUS, validPS] reduce:^id _Nonnull(id first, id second) {
return @([first boolValue] && [second boolValue]);
}];
self.loginCommand = [[RACCommand alloc] initWithEnabled:validLS signalBlock:^RACSignal * _Nonnull(id _Nullable input) {
@strongify(self);
return [[self.user loginSignal] logAll];
}];
}
return self;
}
- (void)bindViewModel {
self.userNameT.text = self.viewModel.user.userModel.username;
self.passWordT.text = self.viewModel.user.userModel.password;
RAC(self.viewModel.user.userModel, username) = self.userNameT.rac_textSignal;
RAC(self.viewModel.user.userModel, password) = self.passWordT.rac_textSignal;
self.loginB.rac_command = self.viewModel.loginCommand;
@weakify(self)
[self.viewModel.loginCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
@strongify(self)
BOOL end = [x boolValue];
[UIApplication sharedApplication].networkActivityIndicatorVisible = end;
if (end) {
[LoadingTool showTo:self.view];
} else {
[LoadingTool hideFrom:self.view];
}
}];
[self.viewModel.loginCommand.executionSignals subscribeNext:^(RACSignal *signal) {
@strongify(self)
[signal subscribeNext:^(ResultModel *model) {
[self.userNameT resignFirstResponder];
[self.passWordT resignFirstResponder];
if (model.success) {
HomeViewController *homeCtr = [HomeViewController homeViewControllerWithViewModel:[[HomeViewModel alloc] initWithHome:[Home homeWithUser:model.dataModel]]];
[UIApplication sharedApplication].delegate.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:homeCtr];
[[UIApplication sharedApplication].delegate.window makeKeyWindow];
} else {
[LoadingTool showMessage:model.message toView:self.view];
}
}];
}];
}
这个方法主要是做了这两件事情,一个是呈现初始化数据;另一个是对控件和数据进行绑定,极大的简化UI与数据的交互,绑定后的能够及时的对数据进行跟新并且能够适时的通知控件。
@interface FriendModel : NSObject
@property (copy, nonatomic) NSString *uin;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *img;
+ (instancetype)friendModelWithInfo:(NSDictionary *)info;
- (instancetype)initWithInfo:(NSDictionary *)info;
@end
这个模型表示,首页好友接口返回的一个好友的数据对象。
@property (strong, nonatomic, readonly) User *user;
+ (instancetype)homeWithUser:(User *)user;
- (instancetype)initWithUser:(User *)user;
- (RACSignal *)friendSignalWithPage:(NSInteger)page andCount:(NSInteger)count;
@end
@interface FriendCellViewModel : NSObject
@property (strong, nonatomic) FriendModel *friendModel;
+ (instancetype)friendCellViewModel:(FriendModel *)model;
- (instancetype)initWithFriendModel:(FriendModel *)model;
@end
从目前来看,这一层毫无用处,仅仅是对model做了一个中转。表面上的确如此,因为这个实力非常简单,对Cell没有复杂的交互和业务。这样的情况是可以整合到一个ViewModel上,可以少写一个Model并不会有任何影响。其实这里面的业务逻辑层已经被减去了。
@interface HomeViewModel : NSObject
@property (copy, nonatomic) NSString *title;
@property (strong, nonatomic, readonly) Home *home;
@property (copy, nonatomic) NSArray *dataArr;
@property (copy, nonatomic)
- (instancetype)initWithHome:(Home *)home;
- (RACSignal *)pageSignal;
@end
分别是表示表题、逻辑模型、结果列表以及一个获取数据的信号方法。
在View层添加FriendTableViewCell、LoginViewController具体就不赘述,与登录类似。
FriendTableViewCell数据绑定,这个也十分简单,这里处理的非常简单,仅仅是对初始化数据进行展示:
- (void)bindViewModel:(FriendCellViewModel *)viewModel {
self.viewModel = viewModel;
self.textLabel.text = self.viewModel.friendModel.name;
self.detailTextLabel.text = self.viewModel.friendModel.uin;
[self.imageView sd_setImageWithURL:[NSURL URLWithString:self.viewModel.friendModel.img] placeholderImage:[UIImage imageNamed:@"50"]];
}
- (void)bindViewModel {
self.title = self.viewModel.title;
@weakify(self)
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[[self.viewModel pageSignal:isDown] subscribeNext:^(ResultModel *model) {
@strongify(self)
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (model.success) {
if (model.dataModel == nil || [(NSArray *)model.dataModel count] == 0) {
[LoadingTool showMessage:isDown ? @"没有数据" : @"没有跟多数据" toView:self.view];
}
} else {
[LoadingTool showMessage:model.message toView:self.view];
}
if (isDown) {
[self.tableView.mj_header endRefreshing];
} else {
[self.tableView.mj_footer endRefreshing];
}
}];
[RACObserve(self.viewModel, dataArr) subscribeNext:^(id _Nullable x) {
@strongify(self)
[self.tableView reloadData];
}];
}
@property (assign, nonatomic, readonly) NSInteger page;
@property (assign, nonatomic, readonly) NSInteger pageCount;
- (RACSignal *)pageSignal:(BOOL)isFirst;
/**
加载tableView
@param isDown 是否为下拉加载
*/
- (void)loadTableView:(BOOL)isDown {
@weakify(self)
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[[self.viewModel pageSignal:isDown] subscribeNext:^(ResultModel *model) {
@strongify(self)
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (model.success) {
if (model.dataModel == nil || [(NSArray *)model.dataModel count] == 0) {
[LoadingTool showMessage:isDown ? @"没有数据" : @"没有跟多数据" toView:self.view];
}
} else {
[LoadingTool showMessage:model.message toView:self.view];
}
if (isDown) {
[self.tableView.mj_header endRefreshing];
} else {
[self.tableView.mj_footer endRefreshing];
}
}];
}
self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
[self loadTableView:YES];
}];
// 设置自动切换透明度(在导航栏下面自动隐藏)
self.tableView.mj_header.automaticallyChangeAlpha = YES;
[self.tableView.mj_header beginRefreshing];
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
[self loadTableView:NO];
}];
self.tableView.mj_footer.automaticallyChangeAlpha = YES;
从上面实现的功能来看,一切都是套路,就不啰嗦了。有兴趣就下载代码看看。