好處:數據與VC層獨立開來捻悯,結構清晰男旗,方便處理球散;
缺點:一個VC對應一個viewModel
-
創(chuàng)建BaseViewModel基類
- block作為回調
typedef void(^QYRequestCompletedBlock)(BOOL success,NSString *error,BOOL hasMoreData,BOOL isBlank);
success:請求成功與否巨缘;
error:錯誤提示添忘;
hasMoreData:能否上拉加載更多;
isBlank:數據是否為空若锁;
typedef void(^QYCacheCompletedBlock)(BOOL success,NSString *error);
success:數據是否為空搁骑;
- 通用數據的定義
//vc直接讀取dataArray
@property (nonatomic, strong) NSMutableArray *dataArray;
//true = 刷新; false = 加載更多
@property (nonatomic, assign) BOOL refresh;
///分頁
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, assign) NSInteger pageSize;
- 實現方法,改變的是pageIndex
- (void)loadLastestPage;//刷新pageIndex=0
- (void)loadNextPage;//加載下一頁pageIndex++
//子類實現具體請求
- (void)loadItemsWithPageNum:(NSInteger)pageNum;
- 緩存的讀取
-(void)getCacheDataWithPath:(NSString*)fileName {
NSArray *array = [QYFileManager readArrayWithFileName:fileName];
[self.dataArray addObjectsFromArray:array];
!self.cacheCompletedBlock ?: self.cacheCompletedBlock(self.dataArray.count>0,nil);
}
-
創(chuàng)建繼承BaseViewModel的viewModel
具體的請求具體而論仲器,可以添加篩選條件煤率;
- 具體方法
- (void)loadItemsWithPageNum:(NSInteger)pageNum {
[super loadItemsWithPageNum:pageNum];
kWeakSelf(self);
[[QYNetManager sharedInstance] loadDataWithParameters:@{@"method":@"info",@"short_conn":@(0)} path:@"api/v1/vpan" methodType:QYRequestType_POST success:^(id responseObject) {
kStrongSelf(self);
if (pageNum == 0) {
self.dataArray = nil;//初始化、忽略緩存
}
//TODO:數據的處理
BOOL hasMoreData = true;//是否數據加載完畢
//data...
if (pageNum == 0) {
//第一頁數據緩存
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
[QYFileManager saveArrayWithPath:self.dataArray fileName:@""];
});
}
!self.requestCompletedBlock ?: self.requestCompletedBlock(true,nil,hasMoreData,self.dataArray.count>0);
} failure:^(NSString *errorInfo) {
kStrongSelf(self);
!self.requestCompletedBlock ?: self.requestCompletedBlock(false,errorInfo,false,false);
}];
}
-
VC調用
一個get方法
- (ViewControllerViewModel *)viewModel {
if (!_viewModel) {
_viewModel = [[ViewControllerViewModel alloc] init];
__block ViewControllerViewModel *temp_viewModel = _viewModel;
kWeakSelf(self);
_viewModel.requestCompletedBlock = ^(BOOL success,NSString *error,BOOL hasMoreData,BOOL isBlank) {
kStrongSelf(self);
[self.tableView.mj_header endRefreshing];
[self.tableView.mj_footer endRefreshing];
if (success) {
if (!hasMoreData) {//是否有更多數據
[self.tableView.mj_footer endRefreshingWithNoMoreData];
}
if (isBlank) {
//數據為空
//TODO:添加缺省頁面
}else {
if (temp_viewModel.refresh) {
//下拉上拉刷新
}else {
//上拉刷新
}
}
}else {
//TODO:給出錯誤提示
}
};
_viewModel.cacheCompletedBlock = ^(BOOL success,NSString *error) {
//緩存
};
}
return _viewModel;
}
注意的是每次下拉刷新的時候手動設置viewModel的refresh為YES