【问题标题】:IOS 13 UIWindow instance is nil during application launchingIOS 13 UIWindow 实例在应用程序启动期间为零
【发布时间】:2019-10-01 13:15:59
【问题描述】:

我正在尝试将我的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
}

有点奇怪。如何解决这个问题?提前致谢。

【问题讨论】:

  • 哪一行????
  • 让 tabController = window!.rootViewController as! UITabBarController
  • 这是 iOS 13 吗?
  • 是的,它在 iOS 13 中

标签: ios swift appdelegate ios13 uiwindow


【解决方案1】:

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应用程序中(_应用程序:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey:Any]?)-> Bool {}。我已经阅读了有关您提到的方法的文档,第二种方法用于非场景配置目的。所以,我应该把数据配置文件放在第二种方法中。我说的对吗?
  • 例如,将来,如果我的应用需要一个单例实例,例如 GPS 定位器,我应该放入 func 场景(_scene: UIScene, willConnectTo session: UISceneSession, options连接选项:UIScene.ConnectionOptions)。对吗?
  • didFinishLaunchingWithOptions 仍然会在willConnectTo 之前被调用,您可以在其中添加任何配置
【解决方案2】:

另一种可能的解决方案

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 2016-11-19
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多