Alternative strings for different targets of same App - use NSLocalizedString?

风格不统一 提交于 2019-12-03 13:17:12

You can have multiple string tables for any given language (that is multiple .strings files). When you want a localised string, you can obtain it through:

NSString *str;

// Look up string in Full.strings
str = [[NSBundle mainBundle] localizedStringForKey:@"SomeKey"
                                             value:@"DefaultValue"
                                             table:@"Full"];

// Look up strings in Lite.strings
str = [[NSBundle mainBundle] localizedStringForKey:@"SomeKey"
                                             value:@"DefaultValue"
                                             table:@"Lite"];

Since the table for this method can be variable, you can even switch it at runtime. The above assumes you have a Full.strings table and a Lite.strings table.

Full.strings

"SomeKey" = "This string appears in the full version";

Lite.strings

"SomeKey" = "This string appears in the lite version";

You may not want to ship them together, if that is the case, you can configure your Info.plist to contain the name of the table to use for a specific target (if you add an entry called "TableToUse", you can get it via [[[NSBundle mainBundle] infoDictionary] objectForKey:@"TableToUse"])

NSLocalizedStrings actually is a macro defined as

#define NSLocalizedString(key, comment) \
        [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]

With table parameter set as nil, the code will use the default one "Localizable" so if we add another localized string file, we should call [[NSBundle mainBundle] localizedStringForKey:value:table: directly instead of calling NSLocalizedStrings

I'd be very hesitant to invent my own language, but you probably don't need to either. If you use NSLocalizedString in the appropriate places and then use genstrings to extract these to a Localizable.strings (see the docs), then you could simple have two versions of this file and then copy the correct version in each target.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!