我在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
都能为我提供正确的英文翻译,但它永远不会更改,并且始终是默认语言。我的代码怎么了?
答案 0 :(得分:1)
在调试宏之前,我会按如下方式设置测试:
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