#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
Performance consideration: avoid Repeated Heap allocation problem
@ObservableObject
allow multiple SwiftUI view tosubscribe
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)
- 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
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
- Scene is new screen or new window instance, think Split view in ipad, windows in macos