我在Prefix.pch中为NSLocalizedString建立一个宏:

#undef NSLocalizedString
#define NSLocalizedString(key,_comment) [[LocalizedText sharedInstance] localizedStringFor:key]


我的LocalizedText类看起来像这样:

+ (LocalizedText *)sharedInstance {
    @synchronized(self)
    {
        if (_singletonInstance == nil)
            _singletonInstance = [[LocalizedText alloc] init];
    }

    return _singletonInstance;
}

- (NSString *) localizedStringFor:(NSString*) key
{

    NSUserDefaults *deviceLanguage = [NSUserDefaults standardUserDefaults];

   NSString *currentLanguage = [deviceLanguage objectForKey:@"deviceLanguage"];

    NSString *path;
    if([currentLanguage isEqual: @"en"])
        path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
    else if([currentLanguage isEqual: @"de"])
        path = [[NSBundle mainBundle] pathForResource:@"de" ofType:@"lproj"];
    else if([currentLanguage isEqual: @"it"])
        path = [[NSBundle mainBundle] pathForResource:@"it" ofType:@"lproj"];


    NSBundle* languageBundle = [NSBundle bundleWithPath:path];
    NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil];

    return str;

}


因此,例如,当我将我的NSUserDefaults更改为@"en"时,我希望每个NSLocalizedString都能给我正确的英语翻译,但它永远不会改变,并且始终是默认语言。我的代码有什么问题?

最佳答案

在调试您的宏之前,我将进行如下测试:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *currentLanguage = [defaults objectForKey:@"deviceLanguage"];

NSString *key = @"SomeKeyFromYourLocalizedFile";
NSString *localized = [[LocalizedText sharedInstance] localizedStringFor:key];
NSLog(@"%@: %@", currentLanguage, localized);

[defaults setObject:@"de" forKey:@"deviceLanguage"];
[defaults synchronize];
NSString *localized = [[LocalizedText sharedInstance] localizedStringFor:key];
NSLog(@"%@: %@", currentLanguage, localized);

[defaults setObject:@"it" forKey:@"deviceLanguage"];
[defaults synchronize];
NSString *localized = [[LocalizedText sharedInstance] localizedStringFor:key];
NSLog(@"%@: %@", currentLanguage, localized);


并查看其输出。您的错误可能在其中。

我预计:

en: English localized
de: German localized
it: Italian localized


之后,您只需使用宏(看起来像那样就可以工作)。我试过了:

#ifdef NSLocalizedString
#undef NSLocalizedString
#endif
#define NSLocalizedString(key, comment) NSLog(@"Output %@, %@", key, comment)

NSLocalizedString(@"First", @"Second");


结果是:
2017-01-12 14:31:31.501 App[49000:50650596] Output First, Second

10-08 06:11