Is it possible to use Core Data in a SwiftUI view that's largely a Swift project? I ask because when I try to get the managed object context from my Swift project into my SwiftUI view all examples are saying it needs to be set first on the top level SwiftUI view like this:
WindowGroup {
ContentView()
.environment(\.managedObjectContext, DataController.shared.container.viewContext)
.environmentObject(coreDataViewModel)
}
Unfortunately, I don't have a top-level SwiftUI view so this is causing problems. Is there another way to set the MOC on the SwiftUI view or am I going to have to nest my initial Swift view inside a SwiftUI view in order to use Core Data?
Yes you can mix UIKit and SwiftUI or any other interface.
Swift is the language they share.
“Top level” can be the first SwiftUI view
AnySwiftUIView()
.environment(\.managedObjectContext, DataController.shared.container.viewContext)
Note that you can also use @ObservedObject
To monitor any CoreData object that is passed in as an argument.
You only have to put it in an environment if the views need to access it.