2016-11-23 2 views
-2

私の問題は、アプリケーションのほとんどのクラスで使用されている定数クラスだから、AppDelegateでそのオブジェクトを作成しました。それから、them.iにアクセスしたいオブジェクトを作成したくありません。毎回どこの定数の。何が最良のアプローチアドバイスをしてください。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-ja-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もしこれを使うには、シングルトン= { せインスタンス=シングルトン() 戻りインスタンス }() プライベートのinit() } ' – KaraBenNemsi

0

文字列のクラスを使用しているだけなので、おそらくシングルトンを使用しないでください。代わりに、おそらくこのような何かのために行ってください:

struct LocalizationConstants { 
    static let settings = NSLocalizedString("Settings", comment: "") 
    static let main = NSLocalizedString("Main", comment: "") 
    static let someString = "value" 
} 
関連する問題