接下来介绍MVVM模式,MVVM = Model + View + ViewModel,当然在iOS中还有一个viewController。
相比起MVC,MVVM多了一个viewModel,而重点就在于viewModel。
顾名思义,viewModel即视图模型,对视图展示数据进行处理,一般流程是,接受vc的事件命令请求及处理相关数据,完事之后将标准展示数据处理好交给vc展示到view上,此谓视图模型。将视图模型分离出来,与视图类做法类似,留出操作接口,协议及代理,这样一来,对于数据层又可以重用,只要vc符合相关的协议,那么在不同的vc中就可以用同一个viewModel了。封装性和重用性得以体现,而且便于测试。
借用歪果人的回答就是: Views display a certain shape of data. They have no idea where the data comes from.
ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
Models hold the actual data (various context, store or other methods)
Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.
时间有限,代码就不贴了。
相关参考和链接附上
1.objc.io
2.http://www.teehanlax.com/blog/model-view-viewmodel-for-ios/
3.stackoverflow:different between MVC MVVM, advantage of MVC,advantage of MVVM
4.github:C-41,MVVM模式的开源项目