看视频时记的笔记。
MVVM架构Model-View-ViewModel
- different from MVC
ModelView Controller
Model
UI independent
- Model does not import swiftUI.
- Model encapsulates
Data
andLogic
. - 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.
- View observes publications.
- 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.
- View calls Intent function.
- ViewModel modifies Model.
- ViewModel publishes, balabalabala.
Syntax
@ObservedObject
@Binding
.onReceive
@EnvironmentObject