我有一个ViewController:ViewController
我有一个AppDelegate:AppDelegate
它们不是通过编程方式制作的,而是在您快速创建新应用时的默认设置。
想象一下,在ViewController中,我有:
class ViewController: UIViewController {
var animal = "dog"
}
例如,当应用程序在后台运行时,我想打印动物值。所以在AppDelegate中,我有:
func applicationDidEnterBackground(_ application: UIApplication) {
var ViewController: ViewController!
print("animal = \(myViewController.animal)")
}
我得到:致命错误:展开一个可选值时意外发现nil
如何从AppDelegate访问该值?
PS:我尝试了google / StackOverflow的前2页
最佳答案
您需要获取rootViewController
func applicationDidEnterBackground(_ application: UIApplication) {
let viewController = self.window?.rootViewController as? ViewController
print(viewController?.animal)
}