QSD的Swift妙妙屋2:妙妙的理论之MVVM

看视频时记的笔记。


MVVM架构Model-View-ViewModel

  • different from MVCModelView Controller

Model

UI independent

  • Model does not import swiftUI.
  • Model encapsulates Data and Logic.
  • Model is the truth.

View

Display

  • Reflect the Model
  • Data flows from Model to View (i.e. read-only)

Stateless

  • View itself does not need to have any state, because all the states about the application are in Model.

Declarative

  • We only need to declare the View to look like this way (create Texts, shapes, etc.).

Old iOS View (before SwiftUI) is Imperative.

Imperative Model

Imperative Model is like an emperor, using commands to put Views on display.

Disadvantages of Imperative Model

Cost time. Functions are called over time, requiring additional dimension of time to know when the function can be called.

However, Declarative is time-independent.

  • Codes are localised.
  • Structs are read-only. The screen will display exactly what you have written.

Reactive

  • Anytime when the Model changes, it asks the Model to look like it (reactive changing).

ViewModel

  • Bind View to Model

Interpreter

  • Help to interpret the Model for the view, thereby keeping the codes in View simple.

Processes Intent

Concept

  • ViewModel processes the Intents of the user(View) to change Model.

Model -> View

How does View notice change in Model?

1. ViewModel notices the changes in Model.

  • Swift can know when a struct is changed.

2. ViewModel might interpret the data into another form.

3. ViewModel publishes "something changed".

  • ViewModel does not talk directly to View. It just publishes.

4. View subscribes to publications.

  1. View observes publications.
  2. When received, View pulls data from Model and rebuilds.

Syntax

ObservableObject
@Published
objectWillChange.send()
.environmentObject()

View -> Model

  • A signal(tapGesture, dragGesture, etc.) from View as an attempt to change Model.
  1. View calls Intent function.
  2. ViewModel modifies Model.
  3. ViewModel publishes, balabalabala.

Syntax

@ObservedObject
@Binding
.onReceive
@EnvironmentObject
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容