在 swift 中,如何在应用程序委托中实现一个变量,以便在应用程序的任何地方检索它?

In swift , how to implement a variable in the app delegate, in order to retrieve it everywhere in the app?

在swift中,如何在应用程序委托中创建一个变量以便在应用程序的任何地方检索它? 我不是在谈论 NSManagedObject

我知道它以 :

开头
let appDelegate = UIApplication.shared.delegate as! AppDelegate

我有一个class个人

class Personne {
var One: String
var Two: Float
}

和另一个 classe 来创建单例:

class PersonneController {
var shared = Personne()

在我的应用程序中,我创建了一个这样的实例:

var personne = Personne()

所以每个变量都通过

检索
personne.shared.myvariable

如何将 personne 放入应用程序委托中,以便从任何地方检索它?

里面class

class AppDelegate..... {
  var name:String?
}

然后

let appDelegate = UIApplication.shared.delegate as! AppDelegate 
print(appDelegate.name)

但是为此最好做一个单例class像

class Service {
  static let shared = Service()
  var name:String?
}

然后

print(Service.shared.name)

甚至将其设为全局变量

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.blabla

1。在 AppDelegate 中创建你的“Personne”实例 Class ( var persnee = Personne())

2。在你的 AppDelegate 中创建一个函数,return AppDelegate

的实例

class func appDelegate() -> AppDelegate {

returnUIApplication.shared.delegate一样! AppDelegate

}

3。你可以这样调用

AppDelegate.appDelegate()。佩斯尼