
請支持原創,如需轉載,請注明出處 @TEASON
最近 MVVM 模式火得一塌糊塗,相信它的出現是為了讓 iOS 開發模塊化。但在我看來,它終究還是 MVC 模式,只是一個變種罷了(當然也有人結合響應式編程的思路實現了顛覆,但我們今天把討論點集中在代碼設計模式上)。
與其費力去講 MVVM 的來歷,不如看一個典型 iOS 項目是如何搭建的,並從中理解 MVVM:
這是一個典型的 MVC 結構:Model 呈現數據,View 呈現界面,View Controller 居中調解二者。
稍加思考就會發現,雖然技術上 View 與 View Controller 是兩個不同組件,但它們幾乎總是成對出現、如影隨形。你何時見過一個 View 能與不同的 View Controller 搭配?反之亦然?既然如此,為何不把它們的連接「正規化」呢?
這更貼切地描述了你可能已經寫過的 MVC 代碼。但它並沒有真正解決 iOS 應用中日益膨脹的「重量級視圖控制器」。在典型的 MVC 應用裡,大量邏輯被塞進了 View Controller:其中一些確實屬於它,但更多的是所謂「用於顯示的邏輯」——用 MVVM 的術語說,就是把 Model 轉換成 View 可呈現形態的那些事,比如把一個 NSDate 格式化成 NSString。
我們的圖裡缺了點東西——一個能安放所有展示邏輯的地方。我們打算稱之為 "View Model",它位於 View/Controller 與 Model 之間:
看起來好多了!這張圖準確描述了 MVVM 的本質:一個 MVC 的增強版——我們正式關聯了視圖與控制器,並把展示邏輯從 Controller 抽出、放進一個新對象 View Model。MVVM 聽着玄乎,實則只是一個精心優化的 MVC 架構,而 MVC 你早已駕輕就熟。
好了,引言說完,這是個鋪墊。
如果你覺得下圖右側那些方法一股腦全塞進 ViewController 更有利於日後維護和擴展,那大可固執己見,然後點擊瀏覽器右上角的「×」……

當然,為 ViewController 瘦身涉及方方面面。今天我們只聚焦一件事:把 TableView 的展示邏輯從 Controller 中剝離出來。之所以先鋪墊 MVVM,是因為其核心思想與此相通——把「邏輯部分」盡量移到 Model 層(你可以把它看作一個中間層)。所謂「邏輯部分」,可以是各種 delegate、網絡請求、緩存、數據庫、Core Data 等等,而 controller 恰恰只用來組織、串聯它們,讓整個程序跑通。
我們很容易想到把 UITableViewDataSource 與 UITableViewDelegate 的代碼抽到一個單獨的類裡。但我發現還有東西可以進一步抽象,比如 cell 的生成、行高、點擊等。這裡我還用 block 的形式實現回調(若你對 block 不太熟悉,建議先補一補)。此外,如果你也重度依賴 .xib 生成 Cell,那我封裝的類會與你非常契合。
記住,我默認習慣用 .xib 文件名作為 cell 的 Identifier。若要用於實戰,請千萬別把 xib 裡 cell 的 Identifier 設錯。
處理類 XTTableDataDelegate 的 .h:
#import
typedef void (^TableViewCellConfigureBlock)(NSIndexPath *indexPath, id item, XTRootCustomCell *cell);
typedef CGFloat (^CellHeightBlock)(NSIndexPath *indexPath, id item);
typedef void (^DidSelectCellBlock)(NSIndexPath *indexPath, id item);
@interface XTTableDataDelegate : NSObject
// 1
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock
cellHeightBlock:(CellHeightBlock)aHeightBlock
didSelectBlock:(DidSelectCellBlock)didselectBlock;
// 2
- (void)handleTableViewDatasourceAndDelegate:(UITableView *)table;
// 3
- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
@end注釋://1. 初始化方法:傳入數據源、cellIdentifier,以及對應配置、行高、點擊的三個 block。
//2. 把 UITableViewDataSource 與 UITableViewDelegate 綁定到 XTTableDataDelegate。
//3. 默認 indexPath.row 對應每個 dataSource,相應返回 item。
此外,為了更徹底,有必要抽象出「根 Cell」。但直接這樣做不利於擴展,為避開 model 與 view 的耦合,我改用 category 來做類的擴展。
#import
@interface UITableViewCell (Extension)
+ (void)registerTable:(UITableView *)table
nibIdentifier:(NSString *)identifier;
- (void)configure:(UITableViewCell *)cell
customObj:(id)obj
indexPath:(NSIndexPath *)indexPath;
+ (CGFloat)getCellHeightWithCustomObj:(id)obj
indexPath:(NSIndexPath *)indexPath;
@end於是通過 UITableViewCell+Extension,用類的擴展來支持新 Cell。
注釋://1 .不解釋。
//2. 根據數據源配置並繪製 cell,子類務必重寫。
//3. 根據數據源計算 cell 高度,子類可重寫,不寫則為默認值 44.0。
#pragma mark - Public
+ (void)registerTable:(UITableView *)table
nibIdentifier:(NSString *)identifier {
[table registerNib:[self nibWithIdentifier:identifier] forCellReuseIdentifier:identifier];
}
#pragma mark - Rewrite these func in SubClass !
- (void)configure:(UITableViewCell *)cell
customObj:(id)obj
indexPath:(NSIndexPath *)indexPath {
// Rewrite this func in SubClass !
}
+ (CGFloat)getCellHeightWithCustomObj:(id)obj
indexPath:(NSIndexPath *)indexPath {
// Rewrite this func in SubClass if necessary
if (!obj) {
return 0.0f; // if obj is null.
}
return 44.0f; // default cell height
}那麼新 cell 類的實現如下——重寫兩個新方法:
- (void)configure:(UITableViewCell *)cell
customObj:(id)obj
indexPath:(NSIndexPath *)indexPath {
MyObj *myObj = (MyObj *)obj;
MyCell *mycell = (MyCell *)cell;
mycell.lbTitle.text = myObj.name;
mycell.lbHeight.text = [NSString stringWithFormat:@"my Height is : %@", @(myObj.height)];
cell.backgroundColor = indexPath.row % 2 ? [UIColor greenColor] : [UIColor brownColor];
}
+ (CGFloat)getCellHeightWithCustomObj:(id)obj
indexPath:(NSIndexPath *)indexPath {
return ((MyObj *)obj).height;
}看下結果:瘦身後的 controller 乾淨得不像實力派,只剩下這一個方法,呵呵呵。
- (void)setupTableView {
self.table.separatorStyle = 0;
TableViewCellConfigureBlock configureCell = ^(NSIndexPath *indexPath, MyObj *obj, XTRootCustomCell *cell) {
[cell configure:cell customObj:obj indexPath:indexPath];
};
CellHeightBlock heightBlock = ^CGFloat(NSIndexPath *indexPath, id item) {
return [MyCell getCellHeightWithCustomObj:item indexPath:indexPath];
};
DidSelectCellBlock selectedBlock = ^(NSIndexPath *indexPath, id item) {
NSLog(@"click row : %@", @(indexPath.row));
};
self.tableHander = [[XTTableDataDelegate alloc] initWithItems:self.list
cellIdentifier:MyCellIdentifier
configureCellBlock:configureCell
cellHeightBlock:heightBlock
didSelectBlock:selectedBlock];
[self.tableHander handleTableViewDatasourceAndDelegate:self.table];
}眾多 .m 文件太過冗長,就不貼到博客了——博客重在講思路,思路才是王道。
當然,若想深入理解,可以去看源碼,我已傳到 github,點我下載。喜歡的話去加個 Star,對開源者是莫大的鼓勵。
有任何疑問或建議,都歡迎留言,我會認真看。
延伸閱讀:介紹 MVVM、Lighter View Controllers、Table View Programming Guide、Cocoa Core Competencies: Controller Object