ios - 如何从 AppDelegate 访问 ViewController 变量

标签 ios swift

我有一个名为 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/

相关文章:

swift - 在 Swift 中测试 Decimal 是否为整数

swift - 添加 reloadRowsAtIndexPaths 的持续时间(快速)

ios - 如何将所有相关的自相关对象放在带有每个关系映射的关联节标题的表格 View 中?

ios - KVO 和上下文可能导致内存泄漏

ios - 支持 64 位,将有效架构设置为 armv8 对吗?

ios - 程序的一部分需要 ARC 而另一部分不需要

arrays - swift 2 : cannot cast value of type NSArray toNSString Dictionary?

swift firebase 从存储中获取图像并在 JSQMessage Controller 中显示

json - Swift 如何从 JSON 中提取 "sort"字典以在时间序列中绘制它?

ios - UITableView,如何以编程方式更改整个表格 View 的宽度和高度?