Best practice using NSLocalizedString
Solution 1
NSLocalizedString
has a few limitations, but it is so central to Cocoa that it's unreasonable to write custom code to handle localization, meaning you will have to use it. That said, a little tooling can help, here is how I proceed:
Updating the strings file
genstrings
overwrites your string files, discarding all your previous translations.
I wrote update_strings.py to parse the old strings file, run genstrings
and fill in the blanks so that you don't have to manually restore your existing translations.
The script tries to match the existing string files as closely as possible to avoid having too big a diff when updating them.
Naming your strings
If you use NSLocalizedString
as advertised:
NSLocalizedString(@"Cancel or continue?", @"Cancel notice message when a download takes too long to proceed");
You may end up defining the same string in another part of your code, which may conflict as the same english term may have different meaning in different contexts (OK
and Cancel
come to mind).
That is why I always use a meaningless all-caps string with a module-specific prefix, and a very precise description:
NSLocalizedString(@"DOWNLOAD_CANCEL_OR_CONTINUE", @"Cancel notice window title when a download takes too long to proceed");
Using the same string in different places
If you use the same string multiple times, you can either use a macro as you did, or cache it as an instance variable in your view controller or your data source. This way you won't have to repeat the description which may get stale and get inconsistent among instances of the same localization, which is always confusing. As instance variables are symbols, you will be able to use auto-completion on these most common translations, and use "manual" strings for the specific ones, which would only occur once anyway.
I hope you'll be more productive with Cocoa localization with these tips!
Solution 2
As for autocompletition for strings in Xcode, you could try https://github.com/questbeat/Lin.
Solution 3
Agree with ndfred, but I would like to add this:
Second parameter can be use as ... default value!!
(NSLocalizedStringWithDefaultValue does not work properly with genstring, that's why I proposed this solution)
Here is my Custom implementation that use NSLocalizedString that use comment as default value:
1 . In your pre compiled header (.pch file) , redefine the 'NSLocalizedString' macro:
// cutom NSLocalizedString that use macro comment as default value
#import "LocalizationHandlerUtil.h"
#undef NSLocalizedString
#define NSLocalizedString(key,_comment) [[LocalizationHandlerUtil singleton] localizedString:key comment:_comment]
2. create a class to implement the localization handler
#import "LocalizationHandlerUtil.h"
@implementation LocalizationHandlerUtil
static LocalizationHandlerUtil * singleton = nil;
+ (LocalizationHandlerUtil *)singleton
{
return singleton;
}
__attribute__((constructor))
static void staticInit_singleton()
{
singleton = [[LocalizationHandlerUtil alloc] init];
}
- (NSString *)localizedString:(NSString *)key comment:(NSString *)comment
{
// default localized string loading
NSString * localizedString = [[NSBundle mainBundle] localizedStringForKey:key value:key table:nil];
// if (value == key) and comment is not nil -> returns comment
if([localizedString isEqualToString:key] && comment !=nil)
return comment;
return localizedString;
}
@end
3. Use it!
Make sure you add a Run script in your App Build Phases so you Localizable.strings file will be updated at each build, i.e., new localized string will be added in your Localized.strings file:
My build phase Script is a shell script:
Shell: /bin/sh
Shell script content: find . -name \*.m | xargs genstrings -o MyClassesFolder
So when you add this new line in your code:
self.title = NSLocalizedString(@"view_settings_title", @"Settings");
Then perform a build, your ./Localizable.scripts file will contain this new line:
/* Settings */
"view_settings_title" = "view_settings_title";
And since key == value for 'view_settings_title', the custom LocalizedStringHandler will returns the comment, i.e. 'Settings"
Voilà :-)
Solution 4
In Swift I'm using the following, e.g. for button "Yes" in this case:
NSLocalizedString("btn_yes", value: "Yes", comment: "Yes button")
Note usage of the value:
for the default text value. The first parameter serves as the translation ID. The advantage of using the value:
parameter is that the default text can be changed later but the translation ID remains the same. The Localizable.strings file will contain "btn_yes" = "Yes";
If the value:
parameter was not used then the first parameter would be used for both: for the translation ID and also for the default text value. The Localizable.strings file would contain "Yes" = "Yes";
. This kind of managing localization files seems to be strange. Especially if the translated text is long then the ID is long as well. Whenever any character of the default text value is changed, then the translation ID gets changed as well. This leads to issues when external translation systems are used. Changing of the translation ID is understood as adding new translation text, which may not be always desired.
Solution 5
I wrote a script to help maintaining Localizable.strings in multiple languages. While it doesn't help in autocompletion it helps to merge .strings files using command:
merge_strings.rb ja.lproj/Localizable.strings en.lproj/Localizable.strings
For more info see: https://github.com/hiroshi/merge_strings
Some of you find it useful I hope.
JiaYow
Updated on June 08, 2020Comments
-
JiaYow almost 4 years
I'm (like all others) using
NSLocalizedString
to localize my app.Unfortunately, there are several "drawbacks" (not necessarily the fault of NSLocalizedString itself), including
- No autocompletition for strings in Xcode. This makes working not only error-prone but also tiresome.
- You might end up redefining a string simply because you didn't know an equivalent string already existed (i.e. "Please enter password" vs. "Enter password first")
- Similarily to the autocompletion-issue, you need to "remember"/copypaste the comment strings, or else
genstring
will end up with multiple comments for one string - If you want to use
genstring
after you've already localized some strings, you have to be careful to not lose your old localizations. - Same strings are scattered througout your whole project. For example, you used
NSLocalizedString(@"Abort", @"Cancel action")
everywhere, and then Code Review asks you to rename the string toNSLocalizedString(@"Cancel", @"Cancel action")
to make the code more consistent.
What I do (and after some searches on SO I figured many people do this) is to have a seperate
strings.h
file where I#define
all the localize-code. For example// In strings.h #define NSLS_COMMON_CANCEL NSLocalizedString(@"Cancel", nil) // Somewhere else NSLog(@"%@", NSLS_COMMON_CANCEL);
This essentially provides code-completion, a single place to change variable names (so no need for genstring anymore), and an unique keyword to auto-refactor. However, this comes at the cost of ending up with a whole bunch of
#define
statements that are not inherently structured (i.e. like LocString.Common.Cancel or something like that).So, while this works somewhat fine, I was wondering how you guys do it in your projects. Are there other approaches to simplify the use of NSLocalizedString? Is there maybe even a framework that encapsulates it?
-
JiaYow about 12 yearsThank you for your answer, I will definitely take a look at your python-file. I agree with your naming conventions. I've talked with some other iOS devs recently, and they recommended the usage of static strings instead of macros, which makes sense. I've upvoted your answer, but will wait a bit before I accept it, because the solution is still a bit clumsy. Maybe something better comes along. Thanks again!
-
ndfred about 12 yearsYou're very welcome. Localization is a tedious process, having the right tools and workflow makes a world of difference.
-
Mike Weller almost 12 yearsI've never understood why gettext-style localization functions use one of the translations as the key. What happens if your original text changes? Your key changes and all your localized files are using the old text for their key. It has never made sense to me. I've always used keys like "home_button_text" so they are unique and never change. I have also written a bash script to parse all my Localizable.strings files and generate a class file with static methods which will load the appropriate string. This gives me code completion. One day I might open source this.
-
Elliot almost 11 yearsWhy static strings instead of macros?
-
ndfred almost 11 yearsWhat would macros give you? They would translate to strings anyway, and declaring them means more code.
-
hiroshi over 10 yearsI think you mean
genstrings
notgestring
. -
Mangesh over 10 yearsGetting ARC errors, No known instance method for selector 'localizedString:comment::(
-
Pascal over 10 yearsI suppose it's because LocalizationHandlerUtil.h is missing. I can't find the code back... Just try to create the header file LocalizationHandlerUtil.h and it should be OK
-
Mangesh over 10 yearsI have created the files. I think it is due to folder path issue.
-
Ronny Webers about 10 yearsyes Steve that is correct. Also, you still need the .strings file method for any dynamically generated string. But only for these, Apple's preferred method is base localisation.
-
Beau Nouvelle about 10 yearsThis is actually quite amazing. No need to create macros.
-
Hyperbole almost 10 yearsLink to the new method?
-
Iulian Onofrei over 9 years@MikeWeller, any progress with it?
-
Martin Gjaldbaek about 9 years@Mike Weller: One advantage to using the localized text from the source language as the key is that there's no risk of changing the source text and forgetting to update the translations. The downside being that you lose the link between the old translations and the new key, so you orphan the now (typically only slightly) out of date translations (and it would be less work to update these than write new ones from scratch). However this is fairly easily solvable by tooling - look for orphaned translations with keys that are a short Levenshtein distance from keys that are missing translations.
-
Allen Zeng over 8 years@ndfred compile time checks that you haven't typed the string wrong is the biggest win. It's marginally more code to add anyway. Also in the case of refactoring, static analysis, having a symbol is going to make things waaay easier.
-
Rafael Nobre about 8 yearsImo the base Localization method is worthless. You still have to keep other location files for dynamic strings, and it keeps your strings spread through a lot of files. Strings inside Nibs/Storyboards can be localized automatically to keys in Localizable.strings with some Libs such as github.com/AliSoftware/OHAutoNIBi18n
-
nodebase over 7 years
NSLocalizedString(@"DOWNLOAD_CANCEL_OR_CONTINUE", @"Cancel notice window title when a download takes too long to proceed");
-- the key is DOWNLOAD_CANCEL_OR_CONTINUE but actual Value is unknown. @ndfred -
petrsyn over 6 years@MikeWeller Agree. That's why it is better to use
NSLocalizedString
with thevalue:
parameter, e.g.NSLocalizedString("btn_yes", value: "Yes", comment: "Yes button")
. This way it is possible to separate the translation ID and the default text. This is how it is used stackoverflow.com/a/45991563/1245231 -
Juanmi almost 4 yearspage not found_
-
hiroshi almost 4 years@Juanmi Thanks for mentioning the dead link. I replaced the link with github url.