swift - 为什么 "var delegate: UIApplicationDelegate?"在 UIApplication 中成为可选项?那会是 fatal error 吗?

标签 swift appdelegate

如果 delegate 属性曾经是 nil,应用将处于不可恢复的状态。

class UIApplication

Declaration
unowned(unsafe) var delegate: UIApplicationDelegate?
Discussion
Every app must have an app delegate object to respond to app-related messages. For example, the app notifies its delegate when the app finishes launching and when its foreground or background execution status changes. Similarly, app-related messages coming from the system are often routed to the app delegate for handling. Xcode provides an initial app delegate for every app and you should not need to change this delegate later.

为什么 UIApplicationDelegate.delegate 被定义为可选的? nil 值是不可恢复的吗?

实际上,如果我将 UIApplication 子类化,那么我可能能够从 delegate 设置为 nil 中恢复?这可能是为什么?

这里是 a related question ,但是 AppDelegate 将整个应用程序结合在一起。我不认为它可能是 nil

最佳答案

一个原因可能是为了防止 AppDelegate 弄乱您的单元测试。

通常,当您运行单元测试时,您实际上不必与绘制在屏幕上的任何 UI 组件进行交互,因此完全没有必要初始化应用程序的 window 属性。此外,在 AppDelegate.swift 中编写的代码(例如 application(application:didFinishLaunchingWithOptions) 中的函数调用)可能会导致您的单元测试无法按预期运行,因此您可能需要永远不会实例化应用程序委托(delegate)。

对于典型的 iOS 应用程序,UIKit 在 main.swift 中创建具有以下功能的应用程序:

UIApplicationMain(Process.argc, Process.unsafeArgv, 
  NSStringFromClass(UIApplication), NSStringFromClass(AppDelegate))

(从 Xcode 6 开始,它由 @UIApplicationMain 装饰器处理。)

UIApplicationMain 初始化应用程序对象和类型为您传递给它的类名的应用程序委托(delegate),并设置事件循环。让它为您创建委托(delegate)对象完全取决于您。如果您不需要 AppDelegate 的 UIWindow 属性,或任何有关处理推送通知、应用程序状态等的回调方法,您可以在没有它的情况下创建应用程序:

UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(UIApplication), nil)

也就是说,如果您的单元测试不依赖于 AppDelegate 的任何方法来运行,您可以按如下方式更新 main.swift:

var delegateClassName: String? = NSStringFromClass(AppDelegate)

if NSClassFromString("XCTestCase") != nil {
 // Unit tests are being run, so don't execute any code written in AppDelegate.swift
 delegateClassName = nil
}
UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(UIApplication), delegateClassName)

关于swift - 为什么 "var delegate: UIApplicationDelegate?"在 UIApplication 中成为可选项?那会是 fatal error 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006946/

相关文章:

ios - 3d touch swift 3 不打开viewcontroller

ios - Xcode 如何在水平堆栈 View 中创建方形按钮(宽度等于高度)

objective-c - 在 Swift 中带有变量的 system() 命令

ios - Swift:即使我切换到不同的 View Controller ,如何使后台功能保持运行

ios - 如何通过应用程序运行计时器进入后台或终止

ios - 通俗地说,我应该如何使用 appdelegate 文件来构建 iOS 应用程序?

ios - 当应用程序处于后台状态 Swift 时暂停计时器

ios - 获取一周的工作日和日期

ios - 如何在swift中用args调用函数 objective-c

ios - 当应用程序从推送通知打开时调用 didFinishLaunchingWithOptions