0

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.

alpennec
  • 1,864
  • 3
  • 18
  • 25
  • Actually no difference here, in first case just better readability. – Asperi Nov 08 '20 at 07:16
  • Thanks! What about the use of Environment for singleton objects? – alpennec Nov 08 '20 at 07:21
  • Environment is a just a way to inject value into view hierarchy, no matter which kind of value: primitive, struct, or pointer to shared object (as in this case). – Asperi Nov 08 '20 at 07:23

0 Answers0