iOS中,我們使用的大部分都是MVC架構雖然MVC的層次明確,但是由于功能日益的增加,代碼的維護,更多的代碼被寫在了Controller中,這樣Controller就顯得非常臃腫。為了給Controller瘦身,后來又從MVC衍生出了一種新的架構模式MVVM架構.
MVVM分別指什么
Model-數據層
ViewController/View-展示層
ViewModel- 數據模型
MVVM與MVC的不同
首先我們簡化一下MVC的架構模式圖:
在這里,Controller需要做太多得事情,表示邏輯、業務邏輯,所以代碼量非常的大。
而MVVM:
比如我們有一個需求:一個頁面,需要判斷用戶是否手動設置了用戶名。如果設置了,正常顯示用戶名;如果沒有設置,則顯示“用戶001”這種格式。(雖然這些本應是服務器端判斷的)
我們看看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:
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做處理。并且Controller里面只負責界面賦值,邏輯處理分發到ViewModel里去,深層次的解耦MVC;
本篇文章轉載自http://www.cnblogs.com/includeao/p/6425091.html,說明了MVVM的設計思路和提供了一個小小的demo,希望對于有MVC經驗的開發者而言,能針對MVVM進行快速入門。(PS:對于復雜的情況,通常使用RAC進行信息傳遞,結合RAC能夠靈活的進行MVVM模式設計框架,網上有一堆資料,后續有時間也會整理一個入門demo)