1

Sorry I am new in Swift, I have a curious question about global sharing ObservableObject

I saw this answer and understand @EnvironmentObject here

https://stackoverflow.com/a/59919052/9585130

Instead using @EnvironmentObject why we don't use like this?

class Person: ObservableObject {
    let shared = Person()
}

Then anywhere in view we can use like below and no need EnvironmentObject any more?

struct BookList: View {
    @ObservedObject var persionViewModel = Person.shared
    ...
}
struct BookView: View {
    @ObservedObject var persionViewModel = Person.shared
    ...
}

Is it impact to memory leak issue?

matt
  • 515,959
  • 87
  • 875
  • 1,141
Binh Ho
  • 3,690
  • 1
  • 31
  • 31

1 Answers1

2

Using @EnvironmentObject injects this dependency into a view and it’s subviews. If at some point the root view (the one the dependency was injected into) gets removed, the environment object will (should) also be deallocated.

So @EnvironmentObject storage is a bit like a service registry rather than a singleton.

Ron
  • 1,610
  • 15
  • 23