iOS中挖藏,我們使用的大部分都是MVC架構雖然MVC的層次明確,但是由于功能日益的增加,代碼的維護意狠,更多的代碼被寫在了Controller中,這樣Controller就顯得非常臃腫疮胖。
為了給Controller瘦身环戈,后來又從MVC衍生出了一種新的架構模式MVVM架構
MVVM分別指什么
Model-數(shù)據(jù)層
ViewController/View-展示層
ViewModel- 數(shù)據(jù)模型
MVVM與MVC的不同
首先我們簡化一下MVC的架構模式圖:
MVC.png
在這里,Controller需要做太多得事情澎灸,表示邏輯院塞、業(yè)務邏輯,所以代碼量非常的大性昭。而MVVM:
MVVM.png
比如我們有一個需求:一個頁面拦止,需要判斷用戶是否手動設置了用戶名檬某。如果設置了串远,正常顯示用戶名;如果沒有設置托享,則顯示“簡書0122”這種格式其兴。(雖然這些本應是服務器端判斷的)
我們看看MVC和MVVM兩種架構都是怎么實現(xiàn)這個需求的
MVC:
Model類:
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, assign) NSInteger userId;
@end
ViewController類:
#import "HomeViewController.h"
#import "User.h"
@interface HomeViewController ()
@property (nonatomic, strong) UILabel *lb_userName;
@property (nonatomic, strong) User *user;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (_user.userName.length > 0) {
_lb_userName.text = _user.userName;
} else {
_lb_userName.text = [NSString stringWithFormat:@"簡書%ld", _user.userId];
}
}
這里我們需要將表示邏輯也放在ViewController中顶瞒。
MVVM:
Model類:
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, assign) NSInteger userId;
@end
ViewModel類:
聲明:
#import <Foundation/Foundation.h>
#import "User.h"
@interface UserViewModel : NSObject
@property (nonatomic, strong) User *user;
@property (nonatomic, copy) NSString *userName;
- (instancetype)initWithUser:(User *)user;
@end
實現(xiàn):
#import "UserViewModel.h"
@implementation UserViewModel
- (instancetype)initWithUser:(User *)user {
self = [super init];
if (!self) return nil;
_user = user;
if (user.userName.length > 0) {
_userName = user.userName;
} else {
_userName = [NSString stringWithFormat:@"簡書%ld", _user.userId];
}
return self;
}
@end
Controller類:
#import "HomeViewController.h"
#import "UserViewModel.h"
@interface HomeViewController ()
@property (nonatomic, strong) UILabel *lb_userName;
@property (nonatomic, strong) UserViewModel *userViewModel;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
_lb_userName.text = _userViewModel.userName;
}
可見,Controller中我們不需要再做多余的判斷元旬,那些表示邏輯我們已經移植到了ViewModel中榴徐,ViewController明顯輕量了很多。
總結:
- MVVM同MVC一樣匀归,目的都是分離Model與View坑资,但是它更好的將表示邏輯分離出來,減輕了Controller的負擔穆端;
- ViewController中不要引入Model盐茎,引入了就難免會在Controller中對Model做處理;