Reputation: 599
I saw in some article that @state has many limitations
I tried to make a struct model and mark it with @state in the contentview (ParentView) and pass this model to its child views by wrapping it with @binding it worked just fine, so i don't understand why we still need @objectbinding as we can pass the same value to these child views and if one change the others will change also? or what are the limitations of @state that @objectbinding solve?
Upvotes: 2
Views: 1100
Reputation: 40659
I recommend you watch WWDC 2019 session: Data Flow in SwiftUI. It is very well explained. It describes in which scenarios @State is perfectly acceptable and where ObjectBinding/EnvironmentObject is necessary instead. The session is only 37 minutes long, but it will be a before and after in your understanding of bindings. Please do watch it, it will save time in the long run.
It all comes down to understanding where is the "source of truth" of your data. This is a concept that is also explained in the video. In a few words, the source of truth is were your data is born. If the data of your variable can be derived from some other variable, then it is not a source of truth.
What are the difference between @State
and @BindableObject
?
@State
: It is local to the view. It has to be a value-type (e.g., a struct, Int, String, Array, etc) and its storage is managed by the framework.
@BindableObject
: It is external to the view, it is a reference value (e.g., a class) and its storage is managed by you, giving you more flexibility to implement your own logic.
Note that @State
variables are also great while prototyping your app. For example, if you are working on the layout of your view, you can initially use a @State
variable to make things easier. Once your view does what you want, you can concentrate on creating your @BindableObject
and replace your @State
.
Upvotes: 5