我有一个名为 ViewController 的 ViewController 我有一个名为 AppDelegate 的 AppDelegate
它们不是以编程方式制作的,它们是您在 swift 中创建新应用程序时的默认设置。
想象一下,在我的 ViewController 中:
class ViewController: UIViewController {
var animal = "dog"
}
例如,我想在应用程序进入后台时打印动物值(value)。所以在 AppDelegate 中我有:
func applicationDidEnterBackground(_ application: UIApplication) {
var ViewController: ViewController!
print("animal = \(myViewController.animal)")
}
我收到: fatal error :在展开可选值时意外发现 nil
如何从我的 AppDelegate 访问该值? PS:我试了google/StackOverflow的前2页
最佳答案
你需要获取 rootViewController
func applicationDidEnterBackground(_ application: UIApplication) {
let viewController = self.window?.rootViewController as? ViewController
print(viewController?.animal)
}
关于ios - 如何从 AppDelegate 访问 ViewController 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42350287/