开发者

iPhone internationalization: falling back to a default language

Consider the following sit开发者_开发技巧uation:

  • We have two Localizable.string files, one in en.lproj and one in it.lproj
  • When the user switches to English or Italian, the proper localized string is loaded using NSLocalizedString(@"keyword", nil)
  • If one of the files is missing the keyword, the string is not retrieved

Is there any way to make this macro load the string from a specific language if it's keyword is not found in the current locale's Localizable.string?


NSLocalizedStringWithDefaultValue function is probably what you need - using it you can specify default value for the case if localization is not found for a given key.


I ran into the same problem. I though it would use the string from the development language strings file if it cannot find a localized string in the user's language, but apparently not.

I ended up creating my own function for getting a localized string.

@interface Localization : NSObject {
    NSBundle* fallbackBundle;
}

- (NSString*) localizedStringForKey:(NSString*)key;

@end


@implementation Localization

- (id)init {
    if (self = [super init]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
        fallbackBundle = [[NSBundle bundleWithPath:path] retain];
    }
    return self;
}

- (void)dealloc {
    [fallbackBundle release];
    [super dealloc];
}

- (NSString*) localizedStringForKey:(NSString*)key {
    NSString* result = [[NSBundle mainBundle] localizedStringForKey:key value:@"!#€NOTFOUND%&/" table:nil];
    if (result == nil || [result isEqualToString:@"!#€NOTFOUND%&/"]) {
        result = [fallbackBundle localizedStringForKey:key value:nil table:nil];
    }
    if (result == nil) {
        result = key;
    }
    return result;
}

@end

You can make a singleton of this and have macros similar to NSLocalizedString that call localizedStringForKey, or something along those lines if you will.


By supplying the second parameter of the NSLocalizedString function, you can specify a string which will be used, if the keyword wasn't found in the Localizable.string.

Is that what you wanted?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜