In Xcode 12 template for a SwiftUI project using Core Data, Apple provides the following code:
import SwiftUI
@main
struct CoreDataApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
In this case, the persistenceController is a singleton.
What's the difference with following code, where the singleton is initialized and passed at the same time? Why do we use a constant for the singleton?
import SwiftUI
@main
struct CoreDataApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
}
}
}
Also, are there any advantages to providing this singleton to the environment? Couldn't we just use PersistenceController.shared.container.viewContext
directly in subviews?
I'm asking because I have few services singletons in my app but I don't want to initialize them from the main App
but in subviews.