3月接近尾声,我们继续深入了解ViewModel
iOS 原生开发工具集并不支持数据绑定,因此我们只能使用第三方库
使用工具 reactCocoa 或者 STCViewModel
都是用于更好的绑定值,监听数据的更新,以显示最新View的第三方库
本文使用的是STCViewModel
1.自定义STCViewModel的子类
2.定义属性(根据需要)
@property (assign, nonatomic, readonly) SEL refreshDataCommand;
@property (nonatomic, strong, readonly) NSArray<Job *> *jobArray;
3.覆盖初始化方法
initWithDelegate
初始化SEL属性 _refreshBannerCommand=@selector(refreshBannerCommand:);
4.实现定义的SEL
- (void)refreshDataCommand:(id)target {
请求数据,获取结果数组
[self reactActionWithTarget:target]; 回调协议方法:reactActionWithViewModel:target
}
1.1 进入 View (将View与ViewModel进行绑定)
1.初始化viewModel
self.refreshTarget =STCGetPropertyName(refreshTarget);
[self.viewModel performSelector:self.viewModel.refreshPersonalSkillsCmd
withObject:self.refreshTarget
afterDelay:0]; 调用ViewModel中已经实现的方法。里面已经实现了网络请求
[self.viewModel registerDelegate:self.fullTimeDataSource];
[self.viewModel bindProperty:STCGetPropertyName(cellDict)
withTarget:self.fullTimeDataSource];
2.View成为STCViewModelProtocol的代理
#pragma mark - STCViewModelProtocol
- (void)reactActionWithViewModel:(id)viewModel target:(id)target {
根据viewModel与target,做出响应
}
-(void)updateValue: withViewModel: target: {
}
2. 进入 self.fullTimeDataSource类中
成为STCViewModelProtocol的代理,实现其updateValue: withViewModel: target:方法
这个方法返回了self.viewModel,可用于给cell赋值