寫這篇文章的目的,是想提供一種思路,幫助大家解決控制器過於臃腫的問題,給控制器「瘦身」。
不妨打開手邊的項目看看,你的控制器有多少行代碼?是不是多到嚇人?再看 tableView 的代理方法 cellForRow 和 heightForRow,是不是也塞滿了 switch 和大量 if-else 判斷?後期維護時看著這些判斷邏輯是不是特別頭疼?尤其是接手前人沒有註釋的代碼時,簡直一團糟。別擔心,這裡提供一種思路,讓你的 tableView 代理方法告別繁瑣的 if-else 判斷,大幅減少控制器代碼量,也大幅降低後期維護成本。
在講具體思路前,先簡單複習一下 MVC 和 MVVM。MVC 大家都很熟悉,分為 Model、View、Controller 三層:Model 負責數據,Controller 負責業務邏輯,View 負責界面顯示,Model 和 View 通過 Controller 橋接交互,擴展性很好。但 MVC 也有缺陷,那就是控制器太臃腫,想在控制器中定位某段邏輯往往很麻煩。
控制器之所以龐大,正是因為 tableView 代理方法裡的 cell 判斷邏輯、網絡請求,以及其他業務邏輯全都堆在控制器裡。於是便有了 MVC 的升級版——MVVM 模式。
MVVM 中,Model 依然負責數據層,Controller 只負責 View 的展示和更新,不再管業務邏輯;View 依然負責界面顯示。那麼原先由 ViewController 承擔的業務邏輯交給誰呢?我們新增一個 ViewModel 層,位於 ViewController 與 Model 之間,專門負責業務邏輯和網絡請求等任務。ViewController 從 ViewModel 取數據並展示到 View 上,不直接和 Model 打交道,直接與 Model 交互的是 ViewModel。

前面都是為理解後文做鋪墊,想深入了解 MVC、MVVM 可自行搜尋,這類文章很多。
那什麼是「面向超類編程」?其實就是圍繞繼承這一特性,讓子類 cell 繼承父類 cell,面向父類這個對象來編程,最終為控制器的 tableView 瘦身。它不僅能優化 tableView,配合 MVVM 新建 ViewModel 還能抽離出很大一部分控制器代碼。下面先對比大家常用的寫法和面向超類的寫法。

老方式大眾寫法
面向超類編程寫法
可能有人會吐槽:新寫法不就比老寫法少了十幾行嗎?其實不然。首先,這個 demo 只寫了三個 cell 作示例,真實項目裡一個控制器的 cell 遠不止三個,cell 越多好處越明顯——因為後期無論添加多少 cell,控制器 tableView 代理方法的代碼幾乎都不會增加,相當於構建了一個模板,只需在新 cell 內部配置即可。其次,真實項目的業務邏輯也不可能這麼簡單,if-else 裡往往嵌套著大量其他邏輯,才會讓 tableView 顯得臃腫。
面向超類編程的好處:
1. 控制器瘦身。【控制器內部代碼量大幅減少,邏輯更清晰】
2. 後期維護成本大大降低。【想增刪 cell 時,只需新建或刪除一個子類 cell,並在 viewModel 中增刪對應的 identifier 即可,控制器幾乎不用改動】
面向超類的壞處:
1. 會新建更多 cell 文件和一個 viewModel 文件,包體積會相應增加。
下面具體講解面向超類編程瘦身大致要做的事。
一、新建一個繼承自 UITableViewCell 的父類 cell
#import <UIKit/UIKit.h> #import "ResponseNewProgrammeData.h" #import "NewProgrammeCellHeightProtocol.h" // 子類需要有回調事件的代理 @protocol NewProgrammeTableViewCellProtocol <NSObject> - (void)cell1DidSelectedRightButton; - (void)cell2DidSelectedRightButton; - (void)cell3DidSelectedRightButton; @end @interface NewProgrammeBaseCell : UITableViewCell <NewProgrammeCellHeightProtocol> @property (nonatomic, weak) id<NewProgrammeTableViewCellProtocol> delegate; @property (nonatomic, strong) ResponseNewProgrammeData *responseNewProgrammeData; @end
首先,要包含控制器的數據源,因為子類 cell 的 UI 等操作全靠這個父類數據源。其次,要實現 NewProgrammeCellHeightProtocol 協議,用於計算高度,具體用法在第二點講解。最後,若子類 cell 有點擊事件需要回調,可再寫一個協議 NewProgrammeTableViewCellProtocol 作為屬性持有,並在控制器中把 delegate 指向控制器作為回調。
二、新建一個 NewProgrammeCellHeightProtocol
#import <Foundation/Foundation.h> // 針對 cell 的高度寫的協議 @protocol NewProgrammeCellHeightProtocol <NSObject> @optional + (BOOL)isStaticCell; + (float)cellHeight; @end
isStaticCell 方法在子類中使用:若當前 cell 是高度固定的靜態 cell,就返回 YES,並在 cellHeight 方法中返回固定高度;否則返回 NO,也無需實現 cellHeight。這兩個方法會在控制器的 heightForRow 中用來計算當前 cell 高度。
三、新建控制器所需的所有 cell,並繼承自剛才的父類 cell
#import "NewProgrammeCell1.h"
@interface NewProgrammeCell1 ()
@property (nonatomic, weak) IBOutlet UILabel *lblName;
@end
@implementation NewProgrammeCell1
@synthesize responseNewProgrammeData = _responseNewProgrammeData;
- (void)setResponseNewProgrammeData:(ResponseNewProgrammeData *)responseNewProgrammeData {
_responseNewProgrammeData = responseNewProgrammeData;
self.lblName.text = _responseNewProgrammeData.string1;
}
+ (BOOL)isStaticCell {
return YES;
}
+ (float)cellHeight {
return 44;
}
- (IBAction)didPressedPush:(id)sender {
if (self.delegate && [self.delegate respondsToSelector:@selector(cell1DidSelectedRightButton)]) {
[self.delegate cell1DidSelectedRightButton];
}
}
@end
這個 cell 高度固定,所以 isStaticCell 返回 YES,cellHeight 返回高度。cell 內部可以拿到控制器數據源,按需要取數據;didPressedPush 方法模擬點擊事件並回調給控制器。其他 cell 的配置大致相同。
四、新建 viewModel 文件
#import "NewProgrammeViewModel.h"
static NSString * const NewProgrammeCell1Identifier = @"NewProgrammeCell1";
static NSString * const NewProgrammeCell2Identifier = @"NewProgrammeCell2";
static NSString * const NewProgrammeCell3Identifier = @"NewProgrammeCell3";
@implementation NewProgrammeViewModel
- (NSArray *)getIdentifierList {
return @[NewProgrammeCell1Identifier, NewProgrammeCell2Identifier, NewProgrammeCell3Identifier];
}
- (void)requestData {
self.responseNewProgrammeData = [[ResponseNewProgrammeData alloc] init];
}
@end
viewModel 負責配置控制器需要註冊的 cell 以及真正要顯示的 cell,getIdentifierList 返回需要註冊的所有 cell。因為某些頁面的 cell 並非固定顯示,可能需要根據數據源動態配置。同時,viewModel 還負責網絡請求、數據解析等業務邏輯。這裡的 viewModel 相當於 MVVM 中的「胖 Model」,既處理網絡請求,又處理頁面 UI 配置等邏輯,從而不讓控制器臃腫。
五、在控制器中做相應代碼配置
- (void)configTableViewCell {
for (NSString *identifer in [self.viewModel getIdentifierList]) {
[self.tableView registerNib:[UINib nibWithNibName:identifer bundle:nil] forCellReuseIdentifier:identifer];
}
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.viewModel.getIdentifierList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [self.viewModel.getIdentifierList objectAtIndex:indexPath.row];
NewProgrammeBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.delegate = self;
cell.responseNewProgrammeData = self.viewModel.responseNewProgrammeData;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [self.viewModel.getIdentifierList objectAtIndex:indexPath.row];
Class<NewProgrammeCellHeightProtocol> cellClass = NSClassFromString(cellIdentifier);
CGFloat height = 0;
if ([cellClass isStaticCell]) {
height = [cellClass cellHeight];
return height;
} else {
NewProgrammeBaseCell *cell = (NewProgrammeBaseCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height;
return height;
}
}
首先,實例化 viewModel 對象,在 configTableViewCell 方法中取出所有需要註冊的 cell 並遍歷註冊。其次,在 cellForRow 代理方法中,從 viewModel 拿到所有 cell 的 identifier,再從 tableView 取出對應的父類 cell 並賦值,充分發揮多態特性,實際調用的是各子類 cell。最後,在 heightForRow 中同樣根據 identifier 反射出子類的類對象,調用協議方法計算高度。
至此,面向超類編程瘦身的整體思路就講完了。