IViewController中获取AppDelegate实例时

IViewController中获取AppDelegate实例时

您好,我一直在查看我的应用的崩溃日志,当我在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

最佳答案

我发现此委托(delegate)是可选值。



所以你应该这样使用它。

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

关于ios - 在其他UIViewController中获取AppDelegate实例时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52001283/

10-10 08:12