Home > database >  @Environment(\.managedObjectContext) vs static let shared property
@Environment(\.managedObjectContext) vs static let shared property

Time:11-08

Are the following two any different?

  1. Using @Environment(\.managedObjectContext) private var moc

  2. Calling PersistentController.shared.container.viewContext when the PersistentController.shared is a static let instance, i.e. static let shared = PersistenceController()

As I currently understand it, static let means one and only instance across the whole application, which is pretty much the same as a singleton.

In my view models I currently pass in moc in the contractors to be used later such as (and I'll call .init(moc) where moc comes from @Environment(\.managedObjectContext))


init(moc: NSManagedObjectContext) {
  self.moc = moc
  //the rest are omitted but you get the idea...
}

And I was wondering if I can simplify it using the static let instance like


init() {
   self.moc = PersistenceController.shared.container.viewContext
}

CodePudding user response:

In general you should always inject dependencies and never access static/global variables directly.

This removes hidden dependencies and tight coupling between different entities of your codebase and also makes unit testing much easier.

It might seem easier to just access a singleton/static instance directly, however, it will make testability and maintenance of your code much harder.

CodePudding user response:

@Environment(\.managedObjectContext) is required by @FetchRequest. It also lets us supply a different context loaded with sample data for previews, e.g.

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
  • Related