I want to get started with Core Data & SwiftUI and therefore created a new watchOS project using the latest Xcode 11.1 GM.
Then, I copied both persistentContainer
& saveContext
from a fresh iOS project (with Core Data enabled), to gain Core Data capabilities.
After that I modified the HostingController
to return AnyView
and set the variable in the environment.
class HostingController: WKHostingController<AnyView> {
override var body: AnyView {
let managedObjectContext = (WKExtension.shared().delegate as! ExtensionDelegate).persistentContainer.viewContext
return AnyView(ContentView().environment(\.managedObjectContext, managedObjectContext))
}
}
Now I can access the context inside the ContentView
, but not in its sub views.
But thats not how it is intended to be? As far as I know, all sub views should inherit its environment from its super views, right?
Right now, to access it inside its sub views I simply set the environment variables again, like this:
ContentView.swift
NavigationLink(destination: ProjectsView().environment(\.managedObjectContext, managedObjectContext)) {
HStack {
Image(systemName: "folder.fill")
Text("Projects")
}
}
Once I remove the .environment() parameter inside ContentView, the App will crash, because there is no context loaded?!
The error message is Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x804795e0>
.
ProjectsView.swift
struct ProjectsView: View {
@Environment(\.managedObjectContext) var managedObjectContext
[...]
}
But again, that can't be right? So, whats causing the error here?