TweetFollow Us on Twitter

Sep 01 Mac OS X

Volume Number: 17 (2001)
Issue Number: 09
Column Tag: Mac OS X

Internationalizing Cocoa Applications - A Primer for Developers and End Localizers

by Andrew C. Stone

Now that you have written that amazing object-oriented Cocoa application, it’s time to bring the fruits of your creativity to the rest of the planet. This article has two components: the steps a developer needs to take to allow the application to be translated, and the steps the translator performs to localize an application to another language. What sets Cocoa localization apart from other development environment localization systems is its pure simplicity. Once an application has been prepared to be localizable by a developer, any number of languages can be added to the final product, without any recompiling by the developer or any access to the source by the parties who are doing the translations. In fact, the localizer can be a regular end user with a love of native language Mac OS X applications! These facts signify that you can ship your application in your native language, and then begin the process of internationalization afterwards. We’ll examine what the developer has to do, and then the steps required by the localizer.

Making An Application Localizable

Translatable text in a graphical user interface appears in two places: the Interface Builder files (nibs) which display menus and interfaces, and the embedded strings that are used in programmatically-created alert and dialog windows. A developer who follows a few guidelines will actually have no additional work to perform to localize their application:

  • Make all programmatic text, alert panel’s titles, messages and buttons use translation macros instead of quoted English strings
  • Always add interface files as localizable resources

Translatable Dictionaries - the .strings files

As you write your code, whenever you use a string that’s going to be displayed to the user, use one of the NSLocalizedString macros (NSLocalizedString, NSLocalizedStringFromTable, NSLocalizedStringFromTableInBundle). When your code is executed, these macros look up the string in a dictionary file with a “.strings” file ending. The .strings file is generated by a command line program, genstrings, that processes your code looking for the macros. Thus, there are three steps to creating the .strings files that get added to the English.lproj (we’ll use English as the native language in this article, although you can develop in any language using Project Builder):

  • Use the NSLocalizedString* macros in your code
  • Run genstrings to generate the .strings files
  • Add the generated files to your PB project as localizable resources

Here is a sample line of code, a message to set what the Undo menu displays once this action has been performed, which will appear in the user’s chosen language:

    [[self undoManager] setActionName:NSLocalizedStringFromTable(@”Change Print Info”, @”Muktinath”, 
    @”Action name for changing print info.”)];

NSLocalizedStringFromTable() takes the string to be displayed (“Change Print Info”), the table to look for the string in (Muktinath.strings), and a helpful comment for the person who is translating the phrase.

Running genstrings on this code would produce an entry in the Muktinath.strings table:\

/* Action name for changing print info. */
“Change Print Info” = “Change Print Info”;
The translator would then make a copy of the .strings file and translate the right hand side. For 
example, en Espaing i
/* Action name for changing print info. */
“Change Print Info” = “Cambiar Info de Imprimir”;

When using the macros in the standard alert panel, one technique to make your code easier to read is to use #defines, which also allows easy reuse:

#define TERMINATE_TITLE NSLocalizedStringFromTable(@”Quit”, @”PackIt”, “Title of alert panel”)

#define TERMINATE_MSG NSLocalizedStringFromTable(@”Remove temporary files?”, @”PackIt”, “Message when 
temp files exist”)

#define CANCEL NSLocalizedStringFromTable(@”Leave alone”, @”PackIt”, “Button title to not remove the 
files”) 

#define OK NSLocalizedStringFromTable(@”OK”,@”PackIt”, “Button choice for OK’ing a requested operation.”)
...
   if (NSRunAlertPanel(TERMINATE_TITLE,TERMINATE_MSG,OK,CANCEL,NULL) == NSAlertDefaultReturn) 
   ...

Generating the Strings files: genstrings

Once you have removed all direct uses of English strings in your program, then you are ready to collect all the translatable strings into their .strings files.

 Type “genstrings” in a terminal window to see its options:

Usage: genstrings [-j] [-s <routine-name>] [-o <output directory>] file1.[mc] ... 
filen.[mc]

Help: genstrings generates .strings file(s) from your source code.
      The names of your source files are the arguments: file1 ... filen.
      * C and Objective-C:
        Source lines with NSLocalizedString(string, comment) will
          generate an appropriate string table entry on Localizable.strings.
        Source lines with NSLocalizedStringFromTable(string, tablename, comment)
          will generate an appropriate string table entry in tablename.strings.
        Source lines with NSLocalizedStringFromTableInBundle(string, tablename, bundle, comment)
          will generate an appropriate string table entry in tablename.strings.
      * Java:
        The -j option sets the expected input language to Java.  In this case the above
          keywords are changed to Bundle.localizedString, Bundle.localizedStringFromTable,
          and Bundle.localizedStringFromTableInBundle (instead of the Objective-C defaults).
      The -s option substitutes its argument for NSLocalizedString.
        For example, -s MyLocalString will catch calls to MyLocalString
        and MyLocalStringFromTable.
      The -o option specifies what directory tables should be created in.

A simple invocation for a multi-level Objective C project would be something like:

genstrings *[hmc] */*[hmc] */*/*[hmc]

All source files in the top three levels would be searched to produce the output strings file. Add the produced .strings files to your resources folder in Groups & Files in Project Builder, and then make them localizable, as described in the next section.

Making Files Localizable

The developer’s second major job is to add all translatable Interface Builder files as “localizable”. In Project Builder:

  • 1. Add the new interface file (Project -> Add Files... or just drop it in to Groups & Files outline view - I like to place .nibs into “Resources”.

If you have saved the .nib file in English.lproj - then steps 2. and 3. are not necessary, otherwise:

  • 2. Project -> Info to bring up interface inspector
  • 3. Click “Localization & Platforms” popup - choose “Make Localized”


Adding other language versions of the interfaces is done with Project->Info with the file to localize selected.

This moves the interface file to the English.lproj in our example. To add a new language version, select the interface file in Groups & Files, choose “Add Localized Variant...” from the “Localization and Platforms” popup and type in the name of the language in English (example, for Espao the English.lproj in our example. To add a new language version, select the interface file in Groups & Files, choose “Add Localized Variant...” from the “Localization and Platforms” popup and type in the name of the languager of the user’s language preferences, if those languages exist in the project. The same procedure applies to .strings files and other resources that require localiization. The localizer now has the resources needed to translate the program.

End User Localization - Anyone can do this!

Localizing an application can be done by anyone who has a basic knowledge of Interface Builder, TextEdit, Terminal and how to open file packages in Finder. Interface Builder comes on the Developer CD that shipped with the original OS X 10.0, so you’ll need to install the Developer package if you haven’t already. A translator doesn’t even need to know how to use InterfaceBuilder if the developer extracts the localizable strings from the interfaces with a special tool, nibtool, described in the Advanced section below.

First, copy the application you wish to localize, just in case you mess something up! Since you will be editing files inside of the Application wrapper, you may to set the permissions so that you’ll be able to save the changes:

  1. Launch /Applications/Utilities/Terminal
  2. Change directory to where you copied the application cd <DIRECTORY>
  3. Change permissions to allow saving: chmod -R a+rwX <APPLICATION>.app

Now, you need to open the application wrapper. In Finder, hold down the control key while clicking on the application file and choose “Show Package Contents” from the contextual menu:


Control-Click an application to open it up

To test your application, set the system language to the one you are localizing. In System Preferences, International Pane, drag the language of choice to the top of the list:


Be sure to set your language before you launch our test application!!

An OS X application has one folder, “Contents”. Inside of that folder is “Resources”. In Resources, you’ll find English.lproj. This folder should be duplicated, and then renamed to the English version of your language, e.g. Spanish.lproj, Dutch.lproj, French.lproj, Japanese.lproj, German.lproj, Italian.lproj, etc.

Now you can edit all the files in your language’s .lproj directory and test your application by launching it anew!


There are three types of files to edit: .strings, .nib, and .html/.rtf informational/help files.

The .strings Files

The most boring task is to convert the strings which appear programmatically: the titles, messages, buttons from alert panels, and the “action names” that the Undo system uses to keep a track of what it’s undoing. (For example, if you change the way the page was layed out, the Edit menu would display “Undo Change Print Info”.) Sophisticated software like Stone Design’s Create® may have hundreds of operations that can be performed, and require translation. Smaller applications may have very few of these, so don’t get discouraged!

These strings appear in .strings files in the .lproj directories. You can use the free, Apple-provided, and Cocoa-based TextEdit program to edit these files; TextEdit supports unicode, the lingua franca of the Cocoa Text system, so all of the special characters found in other languages will be correctly preserved. Because the .strings extension is not registered with TextEdit, double-clicking a .strings file brings up the ‘There is no application available to open the document “Something.strings”- “Choose Application”’ dialog. To avoid this, place TextEdit in your dock, and drag the .strings file on top of the TextEdit icon to quickly open the file.

On the left hand side of a typical entry in the .strings file, the development language string appears, in quotes, followed by an equals sign. The right hand side of the entry is to be replaced by the equivalent phrase in your language. Finally, because these files need to be easily parsed by the application, the entry ends in a semi-colon, and uses /* and */ to delimit comments:

/* Name of Resource Source - like Patterns */
“Pattern” = “Pattern”;

So, the French localizer would translate the second half into:

“Pattern” = “Texture”;

And the Spanish localizer:

“Pattern” = “Motivo”;

And the German localizer:

“Pattern” = “Muster”;

One note about translating strings is the occurrence of format strings within the quotes. The programmer can use %@, %d, %f and other “sprintf”-style placeholders to place runtime information in the programmatically-generated text. For example, the following string will display the name of the pattern:

/* alert message to prevent removal of default pattern */
“You cannot delete the %@ pattern.” = “You cannot delete the %@ pattern.”;

When the program is running, the message would replace the %@ with the actual name of the pattern that cannot be deleted.

The localizer must take care to preserve the number and order of these placeholders. Programmers should make this easier for translators by providing info on the parameters in the comments. In the case of multiple parameters, the parameters are passed in order, and localizers need to keep this mind, even if it means awkward sentence structure, because otherwise, the program will crash! Be careful.

To insert quotes into the quoted string prefix the quote with a backslash: “The word \”quotes\” is quoted.” To insert a single, literal “%” in a string, use “%%”.

Besides the genstrings-produced .strings files, there is also an InfoPlist.strings file which has a few strings that can be localized:

{
    CFBundleGetInfoString = “Stone Design’s Create®. © 1990-2001, Stone Design Corp. 
    Visit www.stone.com”;
    NSHumanReadableCopyright = “© 1990-2001, Stone Design Corp.\nVisit www.stone.com”;
    // Document type human-readable names.
    “Stone Design Graphic Format” = “Stone Create (cre8)”;
    “NSPDFPboardType” = “Portable Document Format (PDF)”;
    “NSTIFFPboardType” = “Tagged Image File Format (TIFF)”;
    CFBundleHelpBookName = “Create Online Manual”;
    CFAppleHelpAnchor = "CreateHelp";
}

By translating the file types such as "NSPDFPboardType", you can have more attractive popups in your Save panels. The CFBundleHelpBookName key controls the display title of the Apple Viewer help your application provides and should be translated.

The Interfaces - Using Interface Builder

Now comes the fun part! Interface Builder lets you open and edit the .nib (NeXT Interface Builder) files, which are the actual interfaces used by a program. To give yourself a real boost, first translate the nib that contains the main menu, usually named the same as the application, e.g. "GIFfun.nib":

The process of converting the IB files goes like this:

for each IB file do:

  • For each string you see, double-click it to edit, and replace with a translated word or phrase
  • If necessary resize the control according to the feedback provided by IB
  • If an interface element has a help tip, translate that as well
    Save and test by quitting and relaunching the application

A few fine points:

  • You can tab between menu and matrix items to increase editing speed
  • To set the title of a window, click on the window, select Tools->Show Info, and select "Attributes" in the popup
  • Note that IB (and OS X) requires that you hit <RETURN> or <TAB> to make your edits "stick".
  • Don’t forget to translate each pane in a TabView: Double-click each tab to make its pane visible

Each interface element can have an attached Help Tip - those cute little yellow windows that pop up if you leave your mouse over a control for a few seconds that describe the functionality of the control. To change these:

  • Select the control
  • Tools->Show Info, "Help" popup pane
  • Enter the tip in your language, and be sure to hit <RETURN> to make it stick

Advanced Localization Topics: Bundles, nibtool and Apple Viewer Help

As usual, the simple life ain’t so simple! One thing to watch for is good engineering on the part of the developer. Cocoa is a dynamic, runtime bound system, which means that objects (code and interfaces) can be loaded upon demand, not when the program starts. In Create®, for example, there are 50 interfaces which are dynamically loaded. This means very fast launch times, and much better memory usage, because you only load resources that you use as you use them. These "bundles" are layed out in a similar manner to the packaging of the application; each .bundle folder contains a Contents folder, which has the Resources folder, which contains an English.lproj with all localizable resources for that bundle. Most bundles just have one nib file — but you need to repeat the process described above (duplicate the English.lproj, rename it to your language in English, and localize the files in the .lproj) for each .bundle folder in the application’s Resources folder.

With the introduction of InterfaceBuilder 2.1, Apple has provided localization capabilities to the command line utility named nibtool (/usr/bin/nibtool). nibtool can extract the localizable strings in a nib to a .strings file, which can be translated, and then reincorporated into a copy of the nib file. This will not adjust spacing of the UI elements so it’s just a start, but it might help things go faster.

To generate the strings file for a particular nib file:

nibtool -L myfile.nib > file.strings

file.strings will now contain entries such as "key" = "key" and be in Unicode (UTF-16) format. Next, give the resulting .strings file to a translator and have them convert the second "key" entry to "key in other language"

To reincorporate these translated strings:

nibtool -d file.strings -w newLocalization.nib myfile.nib

nibtool will take the contents of file.strings and replace "key" in myfile.nib with "something in other language" in the translated version "newLocalization.nib".

The final, and most demanding, part of the translation is the Online Help system - the folder of linked .html files that contains a special "Sherlock-style" index for instant searching. Stone Design keeps our help files in Create®, the localizer then edits the help directly, and produces the HTML with a simple export. This is usually easier than hand-hacking html because you also want to change the screenshots to reflect the translated interfaces. Please read my MacTech article of a few months ago entitled "Help On The Way! A guide for the perplexed on adding Apple Help to your OS X application" for complete instructions on adding online help to an application.

Conclusion

OS X has complete support for internationalization and is simple enough that end users can add new languages. With a small amount of effort, developers can produce applications which can be translated to new languages out in the field, without access to source code, by regular yet adventurous users.


Andrew Stone andrew@stone.com is founder of Stone Design Corp http://www.stone.com/ and divides his time between farming on the earth and in cyperspace.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.