I want to localize a couple of strings in my iPhone app and it works so far for the 5 languages I've selected. However, I have one issue, if I haven't defined a key for a specific language I want it to choose english as a fallback because I know that I have defined every string for sure in english. The thing is that it's not very important that all keys are translated why it's okay to show english even if the iPhone is set to spanish, for instance.

Example:

en:

"HELLO" = "hello" ;
"PERSON" = "my friend" ;

es:

"HELLO" = "hola" ;

Expected Outcome:

If the iPhone is set to english I want it to say: hello, my friend and if the languange is set to spanish I want it to say hola, my friend. Currently the app will output hola, PERSON. (I use the NSLocalizedString method).

There is probably a really easy solution but I couldn't find any good ones. Thanks for the help,

Mattias

有帮助吗?

解决方案

The other answers were definitely correct but it wasn't exactly what I wanted. Instead I found another way to do it and wrote a static method that works perfectly for me in my environment and I wanted to add it here if anybody else wants to acheive the same thing:

+ (NSString *)localizedStringForKey:(NSString *)key table:(NSString *)table
{
    NSString *str = [[NSBundle mainBundle] localizedStringForKey:key value:@"NA" table:table];
    if ([str isEqualToString:@"NA"])
    {
        NSString *enPath = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
        return [[NSBundle bundleWithPath:enPath] localizedStringForKey:key value:@"NA" table:table];
    }

    return str;
}

其他提示

the documentation of the function NSLocalizedString says:

Return Value

The result of invoking localizedStringForKey:value:table: on the main bundle and a nil table.

and for localizedStringForKey:value:table: says:

Return Value

A localized version of the string designated by key in table tableName. If value is nil or an empty string, and a localized string is not found in the table, returns key. If key and value are both nil, returns the empty string.

so you have localize the string for all your languages or change the value of the key you are using

The easy solution is to use the English text as the key. For example:

[NSString stringWithFormat:NSLocalizedString(@"%@, %@", "format for greeting"),
                           NSLocalizedString(@"Hello", "salutation"),
                           NSLocalizedString(@"my friend", "person")]

If there's no localized version of the string, the English key is used.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top