【问题标题】:How to get reference of AppDelegate如何获取 AppDelegate 的引用
【发布时间】: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 了解更多详情

标签: ios swift3 xcode8


【解决方案1】:

这应该可以为 AppDelegate 创建一个对象:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

您可能想要创建一个单例类。

class MySingleton : NSObject
{
  class var sharedInstance :MySingleton
  {
    struct Singleton
    {
        static let instance = MySingleton()
    }

    return Singleton.instance
  }

  final let myVar = "String"
}

然后通过创建对象来访问属性:

let appSingleton = MySingleton.sharedInstance
appSingleton.myVar

这是你想要做的吗?

【讨论】:

  • @NitishaSharma 请检查我的答案,因为您可能应该避免在您的用例中使用单例
  • @igor 我认为如果您想使用单例,这是创建单例的更好方法:final class Singleton { static let sharedInstance: Singleton = { let instance = Singleton() return instance }() private init() { //make it private so nobody can initialise the Singleton from outside } }
  • @igor 更短:final class Singleton { static let sharedInstance = Singleton() private init() { //make it private so nobody can initialise the Singleton from outside } }
  • @KaraBenNemsi。也许,你是对的。我使用了一些关于如何在 Swift 中创建单例的参考资料,上面的代码在我的应用程序中运行良好。但我不是在争论,可能还有其他(更好的)方法来创建它们。干杯!
【解决方案2】:

您可能不应该使用单例,因为您只是将类用于字符串。相反,您可能应该这样做:

struct LocalizationConstants {
    static let settings = NSLocalizedString("Settings", comment: "")
    static let main = NSLocalizedString("Main", comment: "")
    static let someString = "value"
}

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多