iOS 13 应用程序启动期间 UIWindow 实例为空

5

我希望将我的managedObjectContext传递给下一个控制器。我在appDelegate文件中创建了一个UIWindow实例,因为我需要获取我的备用控制器。然而,Xcode说我的UIWindow实例是空的。

这是我的代码:

lazy var managedObjectContext: NSManagedObjectContext = persistentContainer.viewContext

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let tabController = window!.rootViewController as! UITabBarController
    if let tabViewControllers = tabController.viewControllers {
        let navController = tabViewControllers[0]  as! UINavigationController
        let controller = navController.viewControllers.first as! CurrentLocationViewController
        controller.managedObjectContext = managedObjectContext
    }

    return true
}

Debug

enter image description here enter image description here

这有点奇怪。如何解决?提前感谢。


哪一行? - Shehata Gamal
让tabController = window!.rootViewController as! UITabBarController - Nan
这是iOS 13吗? - matt
是的,它在iOS 13中。 - Nan
2个回答

10

iOS 13中的窗口位于SceneDelegate中,而在13之前是位于AppDelegate中。

将代码移动到SceneDelegate中。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let tabController = window!.rootViewController as! UITabBarController
    if let tabViewControllers = tabController.viewControllers {
       let navController = tabViewControllers[0]  as! UINavigationController
       let controller = navController.viewControllers.first as! CurrentLocationViewController
       controller.managedObjectContext = managedObjectContext
     }
}

现在它可以工作了。只是试图弄清楚为什么在 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {} 中不行。我已经阅读了您提到的方法的文档,第二个方法是用于非场景配置目的。因此,我应该将数据配置文件放在第二个方法中。我是对的吗? - Nan
例如,将来如果我需要一个应用程序的单例实例,比如GPS定位器,我应该将其放在func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)中,对吗? - Nan
1
即使在 willConnectTo 之前,仍会调用 didFinishLaunchingWithOptions,您可以在其中添加任何配置。 - Shehata Gamal

7

另一种可能的解决方案

  1. 在你的 AppDelegate.swift 中声明 var window: UIWindow?
  2. 从你的文件中删除 SceneDelegate.swift
  3. Info.plist 中删除 Application Scene Manifest
  4. 在你的 AppDelegate.swift 中使用 window 对象,以便按照你的意愿进行操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接