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

3.9k views Asked by At

I'm building a version of an App I have already released, but with a few changes. It's not quite a lite/full version relationship, but they're similar enough that I'm using the same project with a different target.

I'd like to reword almost all of the strings I have used in the first version for the new version, and was wondering the best way to approach this. Rather than use #ifdef/#else statements before the declaration of each string, I was thinking of using NSLocalizedStrings. However, the actual language is still the same.

I read in this post that you can set the language yourself, so presumably I can invent my own language and set it to that. But I'm wondering if this is the best way to go about things? Any advice would be most welcome.

3

There are 3 answers

2
dreamlax On BEST ANSWER

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"])

10
Martin Gjaldbaek On

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.

0
Qiulang On

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