iOS中,我們使用的大部分都是MVC架構雖然MVC的層次明確,但是由於功能日益的增加,代碼的維護,更多的代碼被寫在了Controller中,這樣Controller就顯得非常臃腫。
爲了給Controller瘦身,後來又從MVC衍生出了一種新的架構模式MVVM架構
MVVM:
Model-數據層
ViewController/View 展示層
ViewModel-數據模型
區別:直接代碼顯示區別:
比如我們有一個需求:一個頁面,需要判斷用戶是否手動設置了用戶名。如果設置了,正常顯示用戶名;如果沒有設置,則顯示“簡書0122”這種格式。(雖然這些本應是服務器端判斷的)
我們看看MVC和MVVM兩種架構都是怎麼實現這個需求的
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中:
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
實現:
#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做處理;