在其他 UIViewController 中获取 AppDelegate 实例时出错

Error when getting AppDelegate instance in other UIViewController

您好,我一直在查看我的应用程序的崩溃日志,当我在 XCode 中打开时,会突出显示以下行

let appDelegate = UIApplication.shared.delegate as! AppDelegate

我很困惑,因为我无法在 XCode 中复制它。应用程序在这里崩溃的可能原因是什么?

这条线在 viewDidAppear() 处,也在 viewDidLoad() 处,但 5 个崩溃报告中有 5 个都指向 viewDidAppear()

处的线

编辑:

这是崩溃日志

Thread 0 name:
Thread 0 Crashed:
0   MyApp                           0x0000000100531208 LoginViewController.initView() + 536 (LoginViewController.swift:107)
1   MyApp                           0x0000000100530d88 @objc LoginViewController.viewDidAppear(_:) + 112 (LoginViewController.swift:58)
2   UIKit                           0x000000018ee2973c -[UIViewController _setViewAppearState:isAnimating:] + 840 (UIViewController.m:4471)
3   UIKit                           0x000000018f07a448 __64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 44 (UIViewController.m:5055)
4   UIKit                           0x000000018ee7f798 -[UIViewController _executeAfterAppearanceBlock] + 92 (UIViewController.m:4793)
5   UIKit                           0x000000018f185990 _runAfterCACommitDeferredBlocks + 564 (UIApplication.m:2528)
6   UIKit                           0x000000018f17b958 _cleanUpAfterCAFlushAndRunDeferredBlocks + 384 (UIApplication.m:2497)
7   UIKit                           0x000000018f18c68c __34-[UIApplication _firstCommitBlock]_block_invoke_2 + 152 (UIApplication.m:9928)
8   CoreFoundation                  0x00000001851372bc __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20 (CFRunLoop.c:1840)
9   CoreFoundation                  0x0000000185136a7c __CFRunLoopDoBlocks + 264 (CFRunLoop.c:1881)
10  CoreFoundation                  0x00000001851347b0 __CFRunLoopRun + 1224 (CFRunLoop.c:2922)
11  CoreFoundation                  0x0000000185054da8 CFRunLoopRunSpecific + 552 (CFRunLoop.c:3245)
12  GraphicsServices                0x000000018703a020 GSEventRunModal + 100 (GSEvent.c:2245)
13  UIKit                           0x000000018f074758 UIApplicationMain + 236 (UIApplication.m:3965)
14  MyApp                           0x0000000100424f3c main + 56 (BaseViewController.swift:19)
15  libdyld.dylib                   0x0000000184ae5fc0 start + 4

我发现这个委托是可选值。

unowned(unsafe) open var delegate: UIApplicationDelegate?

所以你应该这样使用它。

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
    // code here
} else {
    // error handle
}

我终于明白了。崩溃日志都指向这一行

let appDelegate = UIApplication.shared.delegate as! AppDelegate

这是我的 LoginViewController 的第 107 行,但实际错误实际上是由两行之前的一行代码触发的(数据相关错误)。不知道为什么日志都指向第 107 行。感谢您的帮助。