为什么 AppDelegate.swift 窗口是可选的? [英] Why is AppDelegate.swift window an optional?

查看:24
本文介绍了为什么 AppDelegate.swift 窗口是可选的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当时我正在阅读

<小时>

详细概述

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:

The AppDelegate class contains a single property: window.

var window: UIWindow?

This property stores a reference to the app’s window. This window represents the root of your app’s view hierarchy. It is where all of your app content is drawn. Note that the window property is an optional, which means it may have no value (be nil) at some point.

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 窗口是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆