Skip to content
DeveloperMemos

Taking a Look at NSLocalizedString

iOS Development, Localization, NSLocalizedString1 min read

As the world becomes more connected, it's becoming increasingly important for apps to be available in multiple languages. Fortunately, iOS makes it easy for developers to localize their apps with the help of the built-in function NSLocalizedString.

What is NSLocalizedString?

NSLocalizedString is a function provided by Apple's Foundation framework that allows developers to retrieve localized versions of strings from a table in their app's bundle. It takes two arguments: the first argument is the key for the localized string, and the second argument is a comment to help translators understand the context in which the string is used.

Here's an example of how to use NSLocalizedString:

1let title = NSLocalizedString("home.title", comment: "Title for the home screen")

In this example, we're using the key "home.title" to retrieve the localized string for the title of the home screen. If a localized version of this string exists in the app's bundle, it will be returned. Otherwise, the key itself will be returned.

Creating a Localizable.strings File

In order to use NSLocalizedString, you need to create a Localizable.strings file in your app's bundle. This file contains a table of key-value pairs, where the keys are the same strings used in the NSLocalizedString function and the values are the localized versions of those strings.

Here's an example of what a Localizable.strings file might look like:

1"home.title" = "Home";
2"home.subtitle" = "Welcome to my app!";

This file would provide localized versions of the "home.title" and "home.subtitle" strings for your app.

Supporting Multiple Languages

To support multiple languages in your app, you simply need to create additional Localizable.strings files, one for each language you want to support. The filenames for these files should be in the format Localizable.<language_code>.strings, where <language_code> is a two-letter code that represents the language (e.g. en for English, es for Spanish, etc.). XCode will do this for you if you add a language to your project and then select your Localizable.strings file and click "Localize" in the right pane.

Here's an example of what a Localizable.strings file for Spanish might look like:

1"home.title" = "Inicio";
2"home.subtitle" = "¡Bienvenido a mi aplicación!";

To use this file, you would set the user's language preference in your app and iOS would automatically use the appropriate Localizable.strings file to retrieve the localized strings.

Conclusion

NSLocalizedString is a powerful and easy-to-use function that makes it easy for developers to localize their apps for multiple languages. By creating Localizable.strings files and providing localized versions of your app's strings, you can ensure that your app is accessible to users around the world.