Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .strings resource files be added at runtime?

I know that in Mac apps one can add .strings files to the project folder to add localizations.

Is there any way that additional localizations can be added to an app (iOS or Mac OS) without loading them from the resources bundle at compile time. Say, downloading an additional localization and storing it in /Documents on iOS?

like image 395
JoePasq Avatar asked May 20 '11 16:05

JoePasq


1 Answers

Yes, but it's not what you think.

You can take a strings file and load it into an NSString, and then transform it into a dictionary using -[NSString propertyListFromStringsFileFormat].

This will provide you with a way to store your custom-translated strings in-memory.

As for actually using that, you'll have to define custom translation functions. IE, you can't use NSLocalizedString() and friends any more. Fortunately, genstrings (the utility used for generating strings files) lets you specify custom function names:

genstrings -s "JPLocalizedString" ...

This means that in code, you can define:

NSString* JPLocalizedString(NSString *key, NSString *comment) {
  return [myLoadedStrings objectForKey:key];
}

As well as JPLocalizedStringFromTable(), JPLocalizedStringFromTableInBundle(), JPLocalizedStringWithDefaultValue(). genstrings will pick up all of those. (In other words, just because NSLocalizedString is a macro doesn't mean your version has to be)

If you do this and use these JPLocalizedString variants, then genstrings will still generate your strings files for you (providing you use the -s flag).

Once these functions are called, you can use whatever lookup mechanism you want, defaulting back to the NSLocalizedString versions if you can't find anything.

like image 54
Dave DeLong Avatar answered Sep 24 '22 08:09

Dave DeLong