Localizing with different element count
-
05-07-2021 - |
문제
I'd like to give my users a warm welcome, when they are opening my application. So I want to have different sentences to show them randomly. The count of messages differs in each language.
What is the preferred way to solve this problem?
My ideas:
Save the count also in the strings file -> Don't like this idea, because this must be maintained
"welcomeCount" = "5";
"welcomeN" = "Hi....";
Seperating the messages -> Don't like this idea, because you have to mind this
"welcomeMessages" = "Hey there...|MessageN";
Anyone out there with an idea to solve this issue in a elegant manner?
해결책
You can store the welcome messages in localized property lists.
- In Xcode, go to File -> New -> File ...
- Choose the Resource -> Property List template and for example "Welcome.plist" as file name.
- Select Welcome.plist in Xcode and change the type of the root object from Dictionary to Array.
- Select Welcome.plist, to go the File Inspector and click on "Make Localized ...". Then select the localizations that you want for the Welcome.plist., for example English and German.
- Now you have a Welcome.plist for each language which you can edit separately.
- To add strings, click on the "+" symbol in the property list.
In your program, you can load the list easily with
NSString *path = [[NSBundle mainBundle] pathForResource:@"Welcome" ofType:@"plist"];
NSArray *messages = [NSArray arrayWithContentsOfFile:path];
This loads the "right" properly list, depending on the user's language, into the array messages
. You can choose a random message with
int idx = arc4random_uniform([messages count]);
NSString *msg = [messages objectAtIndex:idx];
다른 팁
To minimize maintenance, you can use a binary search to find out how many variations are available. Say you have the following in your Localizable.strings
:
"Welcome_0" = "Hello";
"Welcome_1" = "Hi";
"Welcome_2" = "What up";
"Welcome_3" = "Howdy";
You can find the count using:
int lower = 0, upper = 10;
while (lower < upper - 1) {
int mid = (lower + upper) / 2;
NSString *key = [NSString stringWithFormat:@"Welcome_%i", mid];
BOOL isAvailable = ![key isEqualToString:NSLocalizedString(key, @"")];
if (isAvailable) lower = mid;
else upper = mid;
}
Finally select you random message using:
NSString *key = [NSString stringWithFormat:@"Welcome_%i", rand() % upper];
NSString *welcome = NSLocalizedString(key, @"");