Best practice using NSLocalizedString
Asked Answered
O

9

147

I'm (like all others) using NSLocalizedStringto 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 to NSLocalizedString(@"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?

Ouphe answered 27/3, 2012 at 18:43 Comment(3)
I just do it almost the same like you. But I am using the NSLocalizedStringWithDefaultValue makro to create different strings files for different localization issues (like controllers, models, etc.) and to create an initial default value.Photoreceptor
It seems like xcode6's Export to localization doesn't catch the strings that are defined as macros in a header file. Can anyone confirm or tell me what I might be missing? Thanks...!Pinwheel
@Juddster, can confirm, even with the new fund Editor->Export for Localization it does not get picked up in the header fileEleonoraeleonore
R
101

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!

Roussel answered 17/4, 2012 at 17:49 Comment(11)
Thank 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!Ouphe
You're very welcome. Localization is a tedious process, having the right tools and workflow makes a world of difference.Roussel
I'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.Rosellaroselle
Why static strings instead of macros?Bribery
What would macros give you? They would translate to strings anyway, and declaring them means more code.Roussel
I think you mean genstrings not gestring.Intestine
@MikeWeller, any progress with it?Albarran
@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.Roughandready
@Roussel 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.Prunelle
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. @RousselBicycle
@MikeWeller Agree. That's why it is better to use NSLocalizedString with the value: 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 https://mcmap.net/q/158117/-best-practice-using-nslocalizedstringAshlieashlin
I
31

As for autocompletition for strings in Xcode, you could try https://github.com/questbeat/Lin.

Intestine answered 28/9, 2013 at 2:22 Comment(3)
This is actually quite amazing. No need to create macros.Hydrothermal
page not found_Tragic
@Tragic Thanks for mentioning the dead link. I replaced the link with github url.Intestine
P
25

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à :-)

Pick answered 9/5, 2012 at 9:27 Comment(3)
Getting ARC errors, No known instance method for selector 'localizedString:comment::(Beberg
I 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 OKPick
I have created the files. I think it is due to folder path issue.Beberg
A
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.

Ashlieashlin answered 31/8, 2017 at 23:48 Comment(0)
I
2

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.

Intestine answered 29/9, 2013 at 2:56 Comment(0)
H
2

If anyone looking for a Swift solution. You may want to check out my solution I put together here: SwiftyLocalization

With few steps to setup, you will have a very flexible localization in Google Spreadsheet (comment, custom color, highlight, font, multiple sheets, and more).

In short, steps are: Google Spreadsheet --> CSV files --> Localizable.strings

Moreover, it also generates Localizables.swift, a struct that acts like interfaces to a key retrieval & decoding for you (You have to manually specify a way to decode String from key though).

Why is this great?

  1. You no longer need have a key as a plain string all over the places.
  2. Wrong keys are detected at compile time.
  3. Xcode can do autocomplete.

While there're tools that can autocomplete your localizable key. Reference to a real variable will ensure that it's always a valid key, else it won't compile.

// It's defined as computed static var, so it's up-to-date every time you call. 
// You can also have your custom retrieval method there.

button.setTitle(Localizables.login.button_title_login, forState: .Normal)

The project uses Google App Script to convert Sheets --> CSV , and Python script to convert CSV files --> Localizable.strings You can have a quick look at this example sheet to know what's possible.

Horsefly answered 13/10, 2016 at 6:0 Comment(0)
S
1

with iOS 7 & Xcode 5, you should avoid using the 'Localization.strings' method, and use the new 'base localisation' method. There are some tutorials around if you google for 'base localization'

Apple doc : Base localization

Sparse answered 2/2, 2014 at 16:36 Comment(3)
yes 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.Sparse
Link to the new method?Dena
Imo 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/OHAutoNIBi18nKynthia
M
0
#define PBLocalizedString(key, val) \

[[NSBundle mainBundle] localizedStringForKey:(key) value:(val) table:nil]
Muscadel answered 27/6, 2013 at 9:5 Comment(0)
L
0

Myself, I'm often carried away with coding, forgetting to put the entries into .strings files. Thus I have helper scripts to find what do I owe to put back into .strings files and translate.

As I use my own macro over NSLocalizedString, please review and update the script before using as I assumed for simplicity that nil is used as a second param to NSLocalizedString. The part you'd want to change is

NSLocalizedString\(@(".*?")\s*,\s*nil\) 

Just replace it with something that matches your macro and NSLocalizedString usage.

Here comes the script, you only need Part 3 indeed. The rest is to see easier where it all comes from:

// Part 1. Get keys from one of the Localizable.strings
perl -ne 'print "$1\n" if /^\s*(".+")\s*=/' myapp/fr.lproj/Localizable.strings

// Part 2. Get keys from the source code
grep -n -h -Eo -r  'NSLocalizedString\(@(".*?")\s*,\s*nil\)' ./ | perl -ne 'print "$1\n" if /NSLocalizedString\(@(".+")\s*,\s*nil\)/'

// Part 3. Get Part 1 and 2 together.

comm -2 -3 <(grep -n -h -Eo -r  'NSLocalizedString\(@(".*?")\s*,\s*nil\)' ./ | perl -ne 'print "$1\n" if /NSLocalizedString\(@(".+")\s*,\s*nil\)/' | sort | uniq) <(perl -ne 'print "$1\n" if /^\s*(".+")\s*=/' myapp/fr.lproj/Localizable.strings | sort) | uniq >> fr-localization-delta.txt

The output file contains keys that were found in the code, but not in the Localizable.strings file. Here is a sample:

"MPH"
"Map Direction"
"Max duration of a detailed recording, hours"
"Moving ..."
"My Track"
"New Trip"

Certainly can be polished more, but thought I'd share.

Leaguer answered 7/4, 2016 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.