2016-11-23 61 views
-2

我的问题是我有常量类,它几乎在应用程序中的每个类中使用,所以我通过它在AppDelegate中创建了它的对象n想要访问它们。我不想创建对象常量,每次在哪里,哪些是最好的方法,请咨询。如何获取AppDelegate的参考

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 
}` 
+2

'UIApplicationDelegate'已经是一个独特的实例。千万不要创建它的副本。只需使用其参考。 –

+4

[我如何获得对Swift中应用程序委托的引用?](http://stackoverflow.com/questions/24046164/how-do-i-get-a-reference-to-the-app-快速上传) – Vinodh

+0

在添加重复问题之前进行搜索 – Vinodh

回答

0

这应该创建一个对象的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 

难道这就是你想干什么?

+0

是啊谢谢,这对我有帮助。 –

+0

@NitishaSharma请检查我的答案,因为你应该避免使用单例作为你的用例 – KaraBenNemsi

+0

@igor我认为这是一个更好的方法来创建一个单例如果你想使用一个:'final class Singleton {static} let let sharedInstance:辛格尔顿= { 让实例=辛格尔顿() 回报实例 }() 私有的init(){// 让它私有,这样没有人可以从外面 初始化辛格尔顿} }' – KaraBenNemsi

0

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

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