Hi there!
My code is working, so I don't really have an issue, but I'm still trying to understand how everything works which is why I'm asking this question.
lets say I have a class like this (made up code so I might have missed some part here and there, it's just to illustrate my issue):
class AnObject:ObservableObject{
@Published var id: Int = 0
@Published var name: String = ""
init(){
}
}
Then I have a MainView with a tabview where an environmentObject is created to be used in several places like this:
struct MainView: View {
@StateObject var thisObject = AnObject()
var body: some View {
TabView{
Tab1View().tabItem {Label("ObjectList",systemImage:"list.dash")}
Tab2View().tabItem {Label("OtherView",systemImage:"some.other.icon")}
}
.environmentObject(thisObject)
}
}
And the Tab1View has a list of many AnObject and looks like this:
struct Tab1View:View{
@EnvironmentObject var thisObject:AnObject()
var body: some View {
NavigationView{
List(listOfManyAnObjects) {item in
NavigationLink (destination: NewView().environmentObject(item)){
Text(item.name)
}
}
}
}
}
NewView looks like this:
struct NewView:View{
@EnvironmentObject var thisObject:AnObject
var body: some View {
Text(thisObject.name)
}
}
I have a code similar to this (on another computer, so couldn't copy it) and it shows the correct text, but I'm not entirely sure why.
When you click an object in that list and the new view opens up, will the "thisObject" in the NewView be the same EnvironmentObject as everywhere else in the app, thus having replaced any previous object in that variable? Or will it be a new Instance with the same name? Is there a better way for me to set or change the object in "thisObject" while still using the NavigationLink?