Search code examples
iosswiftcore-dataswiftuienvironment

How to pass CoreData Context to new View presented as a Sheet in Swift 5 using SwiftUI?


I am currently working on a SwiftUI Application that uses CoreData.

This auto-generated Code inside the App File allows me to use the Context in the Content View:

let persistenceController = PersistenceController.shared

ContentView()
    .environment(\.managedObjectContext, persistenceController.container.viewContext)

However, inside my ContentView, I am using the .sheet() Modifier to create a Modal View, which - as far as I know - is a different environment. Therefore I have no access to the Context.

My Question: Is there any solution for passing the Context to the new Environment or do I have to create a new reference to the context like this in my Modal View?

struct ModalView: View {

    let context = PersistenceController.shared.container.viewContext
    ...
}

Thanks for your help.


Solution

  • You can inject it in the same way as you do for ContentView, find below a demo

    struct ContentView: View {
        @Environment(\.managedObjectContext) var moc
    
        var body: some View {
           ...
           .sheet(...) {
               ModalView()
                 .environment(\.managedObjectContext, moc)    // << here !!
           }
        }
    }
    
    struct ModalView: View {
        @Environment(\.managedObjectContext) var moc
    
        // .. other code
    }