Reputation: 966
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?
Upvotes: 0
Views: 122
Reputation: 539685
You can store the welcome messages in localized property lists.
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];
Upvotes: 1
Reputation: 7656
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, @"");
Upvotes: 0