
本篇記錄了一次用 MVVM 思想重構控制器的完整實踐。核心成果是:控制器代碼從原來的 360 行精簡到 159 行。
精簡比例 =(360 − 159)/ 360 ≈ 56%
父類主要承擔三件事,把這些通用能力沉澱到父類後,子類只需調用極少代碼即可復用:
整體代碼量其實增加了 30 多行,但換來的是控制器的清爽——把細節下沉、把職責分離。

1)把網絡請求遷移到 ViewModel
改造前,網絡請求代碼直接堆在控制器裡:
- (void)loadDataForCaseDeatailMsg:(NSString*)caseManageId{
NSMutableDictionary *dict = createMutDict;
[dict setObject:@"case-info" forKey:@"method"];
[dict setObject:caseManageId forKey:@"caseManageId"];
[QTFHttpTool requestPara:dict needHud:YES hudView:self.view loadingHudText:nil errorHudText:nil sucess:^(NSDictionary *json){
BOOL success = (BOOL)[json[@"success"] boolValue];
if(success){
QTCaseDetailModel *caseDetailModel = [[QTCaseDetailModel alloc]init];
caseDetailModel.expertId = json[@"expertId"];
caseDetailModel.userName = json[@"userName"];
caseDetailModel.data = [QTCaseDetailMsgModel objectArrayWithKeyValuesArray:json[@"data"]];
[self gotoChatViewController:caseDetailModel];
}
}failur:^(NSError *error){
}];
}
改造後,控制器只關心自己真正需要的數據,把字典組裝、模型轉換、錯誤處理等細節都交給 ViewModel,5 行就搞定了網絡請求與數據獲取,是不是精簡多了?
- (void)loadDataForCaseDeatailMsg:(NSString*)caseManageId{
[QTCaseDetailViewModel caseDetailhudView:self.view caseManageId:caseManageId getDataSuccess:^(id item, NSInteger totalPage){
[self gotoChatViewController:item];
} getDataFailure:^(NSError *error){}];
}
具體邏輯都在 ViewModel 中實現:添加 hud、完成字典轉模型、對後台數據做錯誤處理與錯誤展示(其中部分能力來自已封裝的底層網絡請求層)。
+ (void)caseDetailhudView:(UIView*)hudView caseManageId:(NSString*)caseManageId getDataSuccess:(GetDataAllSuccessBlock)success getDataFailure:(GetDataFailureBlock)failure{
NSMutableDictionary *dict = createMutDict;
[dict setObject:@"case-info" forKey:@"method"];
[dict setObject:caseManageId forKey:@"caseManageId"];
[QTFHttpTool requestPara:dict needHud:YES hudView:hudView loadingHudText:nil errorHudText:nil sucess:^(NSDictionary *json){
BOOL success1 = (BOOL)[json[@"success"] boolValue];
if(success1){
QTCaseDetailModel *caseDetailModel = [[QTCaseDetailModel alloc]init];
caseDetailModel.expertId = json[@"expertId"];
caseDetailModel.userName = json[@"userName"];
caseDetailModel.data = [QTCaseDetailMsgModel objectArrayWithKeyValuesArray:json[@"data"]];
success(caseDetailModel,1);
}
}failur:^(NSError *error){
}];
}
2)把 dataSource 剝離到獨立文件
以前數據源直接寫在控制器裡,現在獨立成 QTArrayDataSource 類,控制器只需持有並調用即可。它同時兼容 UITableView 與 UICollectionView:
/* 本類作用:用以處理 TableView 以及 CollectionView 的數據源 */
#import <UIKit/UIKit.h>
// 用於配置當前 Cell 的數據
// id cell 表示什麼類型的 Cell
// id item 表示什麼類型的模型對象
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
@interface QTArrayDataSource : NSObject
// 參數1:用以數據源的控制,主要是通過改數組來控制當前 tableView 或者 collectionView 顯示 Cell 的數量
// 參數2:當前需要顯示的 cell 的重用標示
// 參數3:用以配置當前 cell 數據的 block
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
// 通過 indexPath 來獲取當前具體的某一個對象
- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
@end
#import "QTArrayDataSource.h"
#import "QTSpecialCaseCell.h"
@interface QTArrayDataSource ()
// 當前數據數組
@property (nonatomic, strong) NSArray *items;
// 當前 cell 重用標示
@property (nonatomic, copy) NSString *cellIdentifier;
// 當前配置 cell 的 block
@property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;
@end
@implementation QTArrayDataSource
- (id)init {
return nil;
}
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock {
self = [super init];
if (self) {
_items = anItems;
_cellIdentifier = aCellIdentifier;
_configureCellBlock = [aConfigureCellBlock copy];
}
return self;
}
- (id)itemAtIndexPath:(NSIndexPath *)indexPath {
return self.items[(NSUInteger)indexPath.row];
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
// 獲取當前某一行的對象
id item = [self itemAtIndexPath:indexPath];
// 通過調用該 block 配置當前 cell 顯示的內容
self.configureCellBlock(cell, item);
return cell;
}
#pragma mark UICollectionDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.items.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
QTSpecialCaseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifier forIndexPath:indexPath];
// 獲取當前某一行的對象
id item = [self itemAtIndexPath:indexPath];
// 通過調用該 block 配置當前 cell 顯示的內容
self.configureCellBlock(cell, item);
return cell;
}
@end
3)在 viewDidLoad 中以協議方式加載數據源
TableViewCellConfigureBlock configureCell = ^(QTSpecialCaseCell *cell, id data){
[cell configureForCell:data];
};
[_collectionView registerClass:[QTSpecialCaseCell class] forCellWithReuseIdentifier:CellIdentify];
self.arrayDataSource = [[QTArrayDataSource alloc]
initWithItems:self.data
cellIdentifier:CellIdentify
configureCellBlock:configureCell];
self.collectionView.dataSource = self.arrayDataSource;
self.collectionView.delegate = self;
[self refreshOneCreateCollectionView:_collectionView methodSelStr:@"loadData"];
4)仍可繼續探討的部分
