使用SceneDelegate设置CoreData-未知标识符“窗口”错误-iOS 13及更高版本

问题描述 投票:0回答:1

我正尝试使用Apple的官方文档获取Core Data。找到here。我也遇到了一个与我的问题有关的问题,就在stack

我遇到一个问题,它一直说在AppDelegate的上下文中'window'不可用。根据官方文档,这是非常基本的步骤。

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        
    if let rootVC = window?.rootViewController as? ViewController {
        rootVC.container = persistentContainer
    }        
    return true
}

我该如何克服?

core-data ios13 appdelegate uiwindow uiscenedelegate
1个回答
0
投票

问题归结为更改,主要是支持iOS 13及更高版本中的多个场景。检查此reddit link for the discussion

解决方案是将某些东西从AppDelegate移到SceneDelegate。

这是以上两个类别的基本部分的最终形式。

---- SceneDelegate

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    self.window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let rootVC = storyboard.instantiateViewController(identifier: "ViewController") as? ViewController else {
        print("ViewController not found")
        return
    }
    //set the storage here
    rootVC.container = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
    //I dont want a  UI navigation controller.
    //let rootNC = UINavigationController(rootViewController: rootVC)
    //self.window?.rootViewController = rootNC
    //I want to use my basic view controller here. use rootNC to get a UI navigation controller
    self.window?.rootViewController = rootVC
    self.window?.makeKeyAndVisible()

}

-AppDelegate(保持不变)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //before iOS 13 you would be putting stuff here but not anymore.
    return true
}

最后,您将把与存储相关的代码保留在AppDelegate本身中。

© www.soinside.com 2019 - 2024. All rights reserved.