问题描述
当时我正在阅读
详细概述
FWIW,下面的代码不会使用 vc
启动应用程序.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) ->布尔{让 vc = ViewController()window?.rootViewController = vcwindow?.makeKeyAndVisible()返回真}
为什么它不起作用?因为 window
属性是可选的——最初设置为 nil.它需要被实例化
下面的代码会起作用
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) ->布尔{让 vc = ViewController()window = UIWindow(frame: UIScreen.main.bounds)//现在实例化了!!window?.rootViewController = vcwindow?.makeKeyAndVisible()返回真}
I was reading Apple docs, when I found this sentence:
What I don't understand is: why this property at some point could be nil? What's the case for it to be(come) nil?
When you close your application, your app can still receive silentNotifications or download data in the background, track your location, play music, etc.
In the images below, the encircled red are for when your app is still doing something, however it is no longer on the screen. It's in the background, so AppDelegate
doesn't need a window
anymore. As a result it will be set to nil
Simple overview
Detail overview
FWIW, the code below won't make the app launch with vc
.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = ViewController()
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
Why it doesn't work? Because the window
property is an optional—initially set to nil.It needs to be instantiated
The code below will work
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = ViewController()
window = UIWindow(frame: UIScreen.main.bounds) // Now it is instantiated!!
window?.rootViewController = vc
window?.makeKeyAndVisible()
return true
}
这篇关于为什么 AppDelegate.swift 窗口是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!