본문 바로가기

study iOS🍎/CS139P 2023 coursework

CS139P Course4 - class note

 

M-V-VM

MVVM in SwiftUI

 

1. Model notices that itself has changed to ViewModel (swift struct acts on Copy On Write, so Swift can easily detect that the struct has changed when a memory copy happens for a struct)

2. ViewModel Publishes that Model has changed to View

3. View updates the member Views whose body depends on the @Published-keywored struct

 

Concepts used

  • ObservableObject protocol : ViewModel conform to this, by which, it can automatically call 'objectWillChange.send()' without a explicit code, after its @Published-marked struct has changed.
  • @Published : ViewModel should mark structs that it wants to publish to View as this
  • @ObservedObject : View should mark ViewModel as this in order to subscribe to the changes that ViewModel publishes
    • ↔ @StateObject : used for an Object that is initallized within a View. This wrapper means the View owns this object and, the life cycle of the object totally depends on the View that has signed it as @StateObject. So, when the View is loaded the object is initallized and when the View disappears the object gets deinited.
    • On the other hand, @ObservedObject means it's just 'observed' by the View. The object is initallized outside of the View and it just observes the changes that object publishes. The View doesn't own and can't contribute even a bit to the life cycle of the object. 

 

links:

https://www.youtube.com/watch?v=4CkEVfdqjLw