Is there a way to invalidate NSBundle localization cache, withour restarting application? [iOS]

后端 未结 2 730
悲哀的现实
悲哀的现实 2021-01-03 04:43

Let\'s assume that we can change in runtime Localizable.strings, that is placed in NSBundle At the current moment, even if we change it\'s contents, NSLocalizedString

相关标签:
2条回答
  • 2021-01-03 04:49

    NOTE: This solution uses private APIs and your app submissions to the App Store will be rejected if you use this code.

    So, after some search I've found link that helped me

    How to remove NSBundle cache

    // First, we declare the function. Making it weak-linked 
    // ensures the preference pane won't crash if the function 
    // is removed from in a future version of Mac OS X.
    extern void _CFBundleFlushBundleCaches(CFBundleRef bundle) 
      __attribute__((weak_import));
    
    BOOL FlushBundleCache(NSBundle *prefBundle) {
        // Before calling the function, we need to check if it exists
        // since it was weak-linked.
        if (_CFBundleFlushBundleCaches != NULL) {
            NSLog(@"Flushing bundle cache with _CFBundleFlushBundleCaches");
            CFBundleRef cfBundle =
               CFBundleCreate(nil, (CFURLRef)[prefBundle bundleURL]);
            _CFBundleFlushBundleCaches(cfBundle);
            CFRelease(cfBundle);
            return YES; // Success
        }
        return NO; // Not available
    }
    

    After flushing bundle cache, new localizations keys are used. So now I don't need to restart my application in simulator in order to see changes in localizable strings.

    0 讨论(0)
  • 2021-01-03 04:55

    You can use the uncache solution.

    use Localizable.nocache.strings in your lproj folders.

    e.g. example.bundle/Resources/de.lproj/Localizable.nocache.strings

    loading localized strings after getting url via FileManager.

    func localizedString(key: String) -> String {
       let bundle = Bundle(url: bundleUrl)
       return bundle.localizedString(forKey: key, value: nil, table: "Localizable.nocache")
    }
    
    0 讨论(0)
提交回复
热议问题