Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

localization - iOS Change app Language doesn't take effect

I am changing my iOS application preferred language dynamically using this setting:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"ar"] forKey:@"AppleLanguages"];

Then I load a localised resource file from the main NSBundle object, but the loaded file isn't of the new language, it's loaded in the default english language until I restart the application totally then it loads the arabic localisation.

I want to force NSBundle to load the resource file in the new language @"ar" not the language been set when app starts. How?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your method is a hacky way to get what you need, and requires app restart to take effect.

It is best to use NSLocalizedStringFromTableInBundle instead of NSLocalizedString, and provide the bundle for that language.

NSString* path = [[NSBundle mainBundle] pathForResource:@"ar" ofType:@"lproj"];
NSBundle* ar_bundle = [NSBundle bundleWithPath:path];

NSLocalizedStringFromTableInBundle(@"str", nil, ar_bundle, @"comment");

If you put the bundle in a global scope, you can create a macro for ease:

#define ARLocalizedString(str, cmt) NSLocalizedStringFromTableInBundle(str, nil, ar_bundle, cmt)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...