【发布时间】:2016-11-23 11:22:16
【问题描述】:
我的问题是我有常量类,它几乎在应用程序中的每个类中都使用,所以我通过它想要访问它们在 AppDelegate n 中创建了它的对象。我不想每次都创建常量对象.什么是最好的方法请指教。
class AppDelegate: UIResponder, UIApplicationDelegate {
public var constants = Constants()
//created object once in app delegate
}
class Utility
{
let delegate = UIApplication.shared.delegate as! AppDelegate //getting null here
let constants = delegate. constants
}`
【问题讨论】:
-
UIApplicationDelegate已经是一个唯一的实例。永远不要创建它的副本。只需使用它的参考。 -
在添加重复问题之前搜索 SO
-
@Vinodh - 我的问题是我有常量类,它几乎在应用程序的每个类中都使用,所以我已经在 AppDelegate n 中创建了它的对象,因为它想要访问它们。我不想要每次都在每个地方创建常量对象。最好的方法是什么,请咨询。 class AppDelegate: UIResponder, UIApplicationDelegate { public var constants = Constants() //在应用程序委托中创建一次对象 } class Utility { let delegate = UIApplication.shared.delegate as! AppDelegate //这里为空 let constants = delegate.常量}
-
我知道,但上面的代码不是创建常量的好方法。如果您处理 Swift 创建结构并在此处声明所有常量,请使用 SO post stackoverflow.com/a/26252377/1142743 了解更多详情