Friday, July 27, 2012

Force using english localized if current localized does not exists

Create a class:

#undef NSLocalizedString#define NSLocalizedString(key, comment) \
[CLocale localizedString:(key)]
@interface CLocale : NSObject
+ (NSString*) localizedString:(NSString*)key;

#import "CLocale.h"
@implementation CLocale
+ (NSString*) localizedString:(NSString*)key
    NSArray* languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString* currentLocale = [languages objectAtIndex:0];
    NSString* localized = [[NSBundle mainBundle] localizedStringForKey:key value:@"" table:nil];
    // if key and localized are same, also it is not english,
    // then force to use english language
    if ([localized compare:key] == NSOrderedSame && [currentLocale compare:@"en"] != NSOrderedSame)
        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"]];
        localized = NSLocalizedStringFromTableInBundle(key, nil, bundle, nil);
    return localized;

At last, include it into your pre-defined header (.pch)
#import "CLocale.h"


No comments:

Post a Comment