Skip to main content

Data Essential in SwiftUI - 2020

· 2 min read

#learning Data Essential in SwiftUI - 2020

  • @State create a new source of truth
  • @Binding create a reference to the source of truth allow write access to that state

State-Binding

Performance consideration: avoid Repeated Heap allocation problem

CleanShot 2024-03-18 at 08.54.28@2x.png|400

CleanShot 2024-03-18 at 08.54.47@2x.png|400

  • @ObservableObject allow multiple SwiftUI view to subscribe to its changes (specifically before the property will change)
  • ObservableObject protocol is for class (reference type only), which mean it will be kept alive in the memory if there is reference to it
  • Class follow this protocol will usually need to have @Published property that will trigger event that ties to SwiftUI view updates
  • ObservableObject can be used to provide a single source of truth through view / app hierarchy
  • @Published can be used to mark property can be observed or bound to (Binding)

CleanShot 2024-03-18 at 10.09.25.jpg

  • ObservableObject can be used to provide a single source of truth through view / app hierarchy, either as a single Instance (one object) or multiple instances CleanShot 2024-03-18 at 10.19.33.jpg

There is 3 way that View can subscribe to changes of @ObservableObjects

  • @ObservedObject, the life cycle of the observed object is not managed by view life cycle, but somewhere else
  • @StateObject , the object is only initiated just before body of the view is created, and destroyed when the view is no longer rendered. In short, life-cycle of the object is managed by the view
  • @EnvironmentObject is usually used when we want to create a globally shared Source of truth

Data Life-cycle

  • Tied to the way we defined it

CleanShot 2024-03-18 at 10.50.31.jpg

  • Scene is new screen or new window instance, think Split view in ipad, windows in macos