MVVM核心概念

Alt text

MVVM的优势:

  1. 轻量级ViewController和View
  2. UI展现逻辑和业务逻辑分离
  3. 可测试

MVVM各部分职责

Alt text

Model:同MVC中的Model
View(ViewController):同MVC中的View,专注于UI展现逻辑
ViewModel:专注于业务逻辑,网络请求,数据库操作等

MVVM各部分的关系

MVVM各个部分的关系比MVC的更简单,只要严格遵守以下规则:

  1. View(ViewController)可以引用ViewModel,反过来不行
  2. ViewModel可以引用Model,反过来不行

MVVM的核心

双向绑定
View上的一个元素的显示内容和ViewModel中对应的属性值同步更新
The TwoWay binding ensures that changes to the ViewModel’s Username property propagate to the Text property of the TextField, and vice-versa, i.e. user-input is reflected in the ViewModel.