我正在尝试将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
}
有点奇怪。如何解决呢?预先感谢。
答案 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)
var window: UIWindow?
中声明AppDelegate.swift
。SceneDelegate.swift
。Application Scene Manifest
中删除Info.plist
。window
中使用AppDelegate.swift
对象。