代码之家  ›  专栏  ›  技术社区  ›  Andres C

在静态库中从应用程序加载本地化字符串?

  •  0
  • Andres C  · 技术社区  · 12 年前

    我有一个分为多个层的项目,底部的一个作为静态库包含在顶部的一个项目中。

    问题是,我需要使用我的应用程序(上层)中的翻译在静态库中本地化字符串。

    这是可能的吗?

    2 回复  |  直到 12 年前
        1
  •  0
  •   Andres C    12 年前

    我设法做到这一点的方法是从捆绑包中加载字符串,而不是使用 NSLocalizedString :

    + (NSString *)getTranslationFromAppBundleForString:(NSString *)originalText {
    
        NSString * lang = [[NSLocale preferredLanguages] objectAtIndex:0];
        NSString * bundlePath = [[NSBundle mainBundle] pathForResource:lang ofType:@"lproj"];
        NSBundle * bundle = [NSBundle bundleWithPath:bundlePath];
    
        return [bundle localizedStringForKey:originalText value:originalText table:nil];
    }
    
        2
  •  0
  •   Duyen-Hoa    12 年前

    您可以在静态库中创建LanguageAgent,并在该库中添加捆绑资源。然后使用这样的函数获取localizedString。在我的应用程序中,我通过不同的表来分隔语言(参见下图中名为“Dictionaire”的表)。您的语言包中可以有多个表。

    -(NSString*) myLocalizedStringForKey:(NSString*) key ofTable:(NSString*)tableName {
        //I save selected language in my NSUserDefaults.
        NSString *selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
    
        if (selectedLanguage == nil) {
            [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"DefaultLanguage"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
         }
    
        NSString *langBundleNew = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/langs/Languages.bundle/%@.lproj/",selectedLanguage]; //use your path to the Languages.bundle here. 
    
        if ([[NSFileManager defaultManager] fileExistsAtPath:langBundleNew]) {
            NSBundle *aBundle = (NSBundle*)[self.dictLangueBundle objectForKey:selectedLanguage];
             NSString* str=[aBundle localizedStringForKey:key value:@"[string not defined]" table:tableName];
             return str;
        } else {
            return @"[]";
        }
    }
    

    我的语言包类似于:('Dictionaire'=表的名称)

    enter image description here

    下面是我的Dictionnaire.strings中“en.lproj”的内容示例:

    enter image description here