我的字符串扩展在appDelegate之前运行,为什么会这样?

时间:2018-05-25 11:07:39

标签: swift appdelegate

appDelegate didFinishLaunchingWithOptions中,我将值存储在UserDefaults中,如下所示:

  UserDefaults.standard.setValue("fr", forKey: "selectedLocale")

我有extension String UserDefaults我访问nil之前存储的值,但我得到了func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool。当我尝试调试代码时,我知道扩展程序在 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /*----------------- Setting Locale on App Launch ------------------*/ // UserDefaults.standard.setValue((UserDefaults.standard.value(forKey: "AppleLanguages") as! [Any])[0], forKey: USER_DEFAULT.selectedLocale) let country = NSLocale.current if let locale = country.collatorIdentifier { if locale.contains("en") { Singleton.sharedInstance.currentLocale = "en" } else { Singleton.sharedInstance.currentLocale = "fr" } } else { Singleton.sharedInstance.currentLocale = "fr" } Singleton.sharedInstance.isRTL = false UserDefaults.standard.setValue(Singleton.sharedInstance.currentLocale, forKey: USER_DEFAULT.selectedLocale) }

之前运行

任何人都可以解释为什么会这样吗?

提前完成

我的代码如下:

适用于appDelegate:

  extension String {
        var localized: String {
              let locale = UserDefaults.standard.value(forKey: USER_DEFAULT.selectedLocale) as? String
              if let path = Bundle.main.path(forResource: locale, ofType: "lproj") {
                    let bundle = Bundle(path: path)
                    return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
              }
        return self
        }
  }

对于扩展程序:

left

1 个答案:

答案 0 :(得分:1)

当你的任何字符串初始化时,你的extension String会调用。在您的代码中currentLocale。对于我的意见,您需要在extension中创建函数,并在存储值时调用它。

UserDefaults.standard.setValue(Singleton.sharedInstance.currentLocale, forKey: USER_DEFAULT.selectedLocale) 
Singleton.sharedInstance.currentLocale.loadNib() //function in extension

例如

extension String {
     func loadNib() {
         let locale = UserDefaults.standard.value(forKey: USER_DEFAULT.selectedLocale) as? String
         if let path = Bundle.main.path(forResource: locale, ofType: "lproj") {
            let bundle = Bundle(path: path)
            return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
          }
    }
}