我想为我的应用实现多语言支持。所以我创建了Localizing.strings
文件和所有内容并翻译了我的界面。到目前为止一切都很好......
现在我想复制我的数据库,以便为每种语言提供* .db文件。所以我做了,然后我通过XCode点击了Localization选项卡下的“+”。我现在在en.lproj
和de.lproj
文件夹中有一个* .db文件。
我的问题:如果我想将db-files复制到app的文档目录中,* .db文件当然不可用,因为它位于* .lproj文件夹中。有没有命令来获取正确的lproj文件夹?
澄清我的需求: 这不起作用
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydatabase.db"]
......这样做:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"de.lproj/mydatabase.db"]
...但我不想手动添加“de.lproj”和“en.lproj”等。有没有办法动态修复它?
答案 0 :(得分:3)
只需执行以下操作:
NSString *dbpathResource =
[[NSBundle mainBundle] pathForResource:@"databaseName" ofType:@"db"];
如果你在xx.lproj中有你的本地化.db文件,那么将采用正确的数据库。
答案 1 :(得分:2)
您想要的是当前语言区域设置,以下代码应返回代码:
NSArray *languagesArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languagesArray objectAtIndex:0];
然后您可以执行以下操作
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.lproj/mydatabase.db", currentLanguage]];
您可能想检查路径是否存在且是否是有效文件,否则可能会使用某些默认路径,例如英语(en.lproj)
编辑:还有另一种方法可以使用NSLocale的首选语言来完成此操作,因为这样您就可以获得首选语言的列表,因此第一位的一些更新代码将是:
NSArray *languagesArray = [NSLocale preferredLanguages];
NSString *currentLanguage = [languagesArray objectAtIndex:0];
最后,你最终会得到类似的东西:
NSString *pathComponent = [NSString stringWithFormat:@"%@.lproj/mydatabase.db", currentLanguage];
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:pathComponent];
NSString *activePath = nil; // This will store the active language file
// Check if the file exists...
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
activePath = path;
} else {
activePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"en.lproj/mydatabase.db"]; // Fallback
}
请注意,上述代码未经测试但应该足够了。您可能需要稍微修改一下......
答案 2 :(得分:1)
这样的事情:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * rootPath = [[NSBundle mainBundle] resourcePath];
NSString * resourcePath = [[NSBundle mainBundle] pathForResource: @"mydatabase" ofType: @"db" inDirectory: rootPath forLocalization: language];