MVVM
MVC 雖然一直是蘋果建議的一種設計模式,但是 View 與 Controller 的耦合度過高矢洲,而 Controller 往往會變得越來越臃腫弓候,因此常被戲稱為 Massive View Controller(重量級視圖控制器)。
于是 MVVM (Model-View-ViewModel)應運而生 玻淑。
既然View 與 Controller 的耦合度總是過高育拨,那么不如就將它們正式連接起來亚皂,并將表示邏輯(presentation logic)抽離出來形成 ViewModel吠式。其本質上是優(yōu)化后的 MVC 架構茁彭。
so , talk is cheap show me the code
這是一個簡單的 PersonModel
@interface PersonModel : NSObject
- (instancetype)initwithSalutation:(NSString *)salutation
firstName:(NSString *)firstName
lastName:(NSString *)lastName
birthdate:(NSDate *)birthdate;
@property (nonatomic, readonly) NSString *salutation;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate *birthdate;
@end
對應的 PersonalViewModel
@interface PersonalViewModel : NSObject
- (instancetype)initWithPerson:(PersonModel *)person;
@property (nonatomic, readonly) PersonModel *person;
@property (nonatomic, readonly) NSString *nameText;
@property (nonatomic, readonly) NSString *birthdateText;
@end
內部實現(xiàn)总寒,將原本在 controller 中的工作抽離出來
@implementation PersonalViewModel
- (instancetype)initWithPerson:(PersonModel *)person {
self = [super init];
if (!self) return nil;
_person = person;
if (person.salutation.length > 0) {
_nameText = [NSString stringWithFormat:@"%@ %@ %@",
self.person.salutation,
self.person.firstName,
self.person.lastName];
} else {
_nameText = [NSString stringWithFormat:@"%@ %@",
self.person.firstName,
self.person.lastName];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
_birthdateText = [dateFormatter stringFromDate:person.birthdate];
return self;
}
現(xiàn)在 controller 中就變得十分精簡了
// 變得非常輕量的賦值
self.nameLable.text = self.viewModel.nameText;
self.birthdateLabel.text = self.viewModel.birthdateText;
MVVM 總結
通過學習感覺 MVVM 并不是一種新奇的設計模式,它更像是 MVC 的一種完善理肺,核心思想在于抽離復雜的業(yè)務邏輯產生 viewModel 層摄闸,降低耦合度。而使 MVVM 實現(xiàn)響應式編程妹萨,變得更加好用年枕,可以引入 ReactiveCocoa 的 配合。
參考資料:
- Limboy’s HQ ReactiveCocoa與Functional Reactive Programming
- ObjC 中國 - MVVM 介紹
- MVVM With ReactiveCocoa - 簡書
- Barbara Oakley: “Learning How to Learn” | Talks at Google - YouTube
- Limboy’s HQ
- iOS 7 Best Practices; A Weather App Case Study: Part 1/2 一個外國小哥寫的天氣app乎完,方便理解
- 基于ReactiveCocoa和MVVM設計的購物車基本操作實現(xiàn)代碼解析 | 喬同X的博客