Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...