我遵循了Onboarding屏幕的教程,但是似乎它主要是UIKit的改编,在AppDelegate
上,我收到以下紫色错误:
Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x6000018d5880>
我相信这是在SceneDelegate中设置的方式,不将managedObjectContext传递到下一个屏幕,这是我的操作方式:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
// Set the MotherView as the root view
window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(ViewRouter()))
self.window = window
window.makeKeyAndVisible()
}
}
如果我不使用核心数据,那行得通。如何在此处集成ViewRouter():
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Get the managed object context from the shared persistent container.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(\.managedObjectContext)` in the views that will need the context.
let contentView = MotherView().environment(\.managedObjectContext, context)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
// Set the MotherView as the root view
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
我去了this帖子,但它对我没有帮助,有什么办法可以在SceneDelegate中解决此问题?
答案 0 :(得分:1)
在任何地方将环境对象附加到构造的内容视图中,例如如下所示
let contentView = MotherView()
.environment(\.managedObjectContext, context)
.environmentObject(ViewRouter())