如何从任何特定的视图控制器访问 UIApplicationDelegate?

How do I access the UIApplicationDelegate from any particular view controller?

场景: 我想在可从视图控制器访问的 App Delegate 中设置一个布尔标志。

如何从任何视图控制器访问此标志?

当你说 "within the AppDelegate" 时,你的意思是作为实例 属性 吗?如果应用委托 class 是 AppDelegate,那么它的实例是 UIApplication.shared.delegate as! AppDelegate,并且它可能拥有的任何实例属性都可以通过该引用访问。

但是如果你只是指"in the file AppDelegate.swift but outside the AppDelegate class itself",那么这个变量是一个全局变量,可以从任何地方直接访问。

您只需在委托中创建标志并像这样访问它:

let appDelegate = UIApplication.shared.delegate as! AppDelegate