【问题标题】:Setup managedObjectContext on SceneDelegate SwiftUI在 SceneDelegate SwiftUI 上设置 managedObjectContext
【发布时间】:2020-05-20 19:42:04
【问题描述】:

我按照入门屏幕教程进行操作,但似乎它主要是 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 中解决这个问题?

【问题讨论】:

标签: swift swiftui


【解决方案1】:

在任何地方将环境对象附加到构造的内容视图中,例如如下

let contentView = MotherView()
                     .environment(\.managedObjectContext, context)
                     .environmentObject(ViewRouter())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多