在应用程序启动期间,IOS 13 UIWindow实例为零

时间:2019-10-01 13:15:59

标签: ios swift appdelegate ios13 uiwindow

我正在尝试将managedObjectContext传递给下一个控制器。 我需要在appDelegate文件中固有一个UIWindow实例,因为我需要获得备用控制器。 但是,Xcode说我的UIWindow实例为nil。

这是我的代码:

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

有点奇怪。如何解决呢?预先感谢。

2 个答案:

答案 0 :(得分:4)

  

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
     }
}

答案 1 :(得分:2)

另一种可能的解决方案

  1. 在您的var window: UIWindow?中声明AppDelegate.swift
  2. 从文件中删除SceneDelegate.swift
  3. Application Scene Manifest中删除Info.plist
  4. 根据需要在window中使用AppDelegate.swift对象。