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

my extension of string runs before appDelegate why this happens?

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

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

我有一个 Stringextension,我可以在其中访问我之前存储在 UserDefaults 中的值,但在那里我得到了 nil。当我尝试调试代码时,我知道扩展名是 运行 在 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

之前

谁能解释为什么会这样?

提前致谢

我的代码如下:

对于 appDelegate:

  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)
  }

以及扩展:

  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
        }
  }

您的 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: "")
          }
    }
}