I attached an image. Please see it.
As far as I know the "View" is only view. It’s not controller.
So Im developing like Way 1.
But I faced a problem that how can I use observableobject in another observableobject?
I thought if I pass a parameter with the observableobject the problem will be clean.
But I think it is bad way..
So I thought way 2.
But the way is the "View" is not only view. It is view and controller.
So Im confused the way2 is bad way or not.
Which way is good way? and Im wondering other SwiftUI developers how to develop about this case.
Please advice me if you think there is better way than way1 & way2.
Summary
Q1. Way1 – How can I use observableobject in another observableobject? (singltone? like static shared)
Q2. Way2 – Is it correct way? (View = view + controller)
Q3. Your advice.
Env
Xcode 14.2
Swift 5.7.2
2
Answers
Here is the sample code for your question:
ObservableObjects
are mostly used where there is nesting of viewsSwiftUI is a new architecture, old design patterns don’t really fit. In SwiftUI the
View
struct isn’t the view in the MVC sense, that view layer (e.g. UIView/NSView objects) is generated automatically for us based diffing theView
structs which are super fast efficient value types. View state is held in property wrappers like@State
which essentially makes the value behave like an object, e.g. it has a "memory". You can pass this down to sub-Views aslet
for read access or@Binding var
for write access, SwiftUI will track dependencies and callbody
on the affectedView
structs when necessary.Normally in SwiftUI we only have a single
ObservableObject
that holds the model structs in@Published
properties. Usually there are 2 singletons, oneshared
that loads from disk and anotherpreview
pre-loaded with test data for driving SwiftUI previews. This object is shared across View structs using.environmentObject
If you attempt to use multiple
ObservableObject
for view data instead of@State
you’ll run into major problems, actually the kind of consistency problems that SwiftUI’s use of value types was designed to eliminate.