多语言的多个SQLite数据库?
问题描述:
我想为我的应用程序实现多语言支持。所以我创建了Localizing.strings
文件和所有这些东西并翻译了我的界面。到目前为止好...多语言的多个SQLite数据库?
现在我想重复我的数据库,以便有一个* .db的文件为每一个语言。所以我做了,然后在“本地化”选项卡下的“+”上通过XCode单击。我现在在我的en.lproj
和de.lproj
文件夹中有一个* .db文件。
我的问题:如果我想将DB-文件复制到应用程序的文件目录下的* .db文件不可用,当然,因为它是在*的.lproj文件夹。有没有任何命令来获得正确的lproj文件夹?
为了澄清我的需求: 这不起作用
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydatabase.db"]
...这样做:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"de.lproj/mydatabase.db"]
...但我不想添加 “de.lproj” 和“ en.lproj“等手动。有什么办法可以动态修复它吗?
答
你想要什么是当前的语言环境,下面的代码应返回的代码:
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
}
请注意,上面的代码没有经过测试,但应该足够了。您可能需要修改它有点...
答
事情是这样的:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * rootPath = [[NSBundle mainBundle] resourcePath];
NSString * resourcePath = [[NSBundle mainBundle] pathForResource: @"mydatabase" ofType: @"db" inDirectory: rootPath forLocalization: language];
答
只是做到以下几点:
NSString *dbpathResource =
[[NSBundle mainBundle] pathForResource:@"databaseName" ofType:@"db"];
,如果你在XX本地化.db文件。 lproj所以正确的数据库将被采取。
真棒答案!非常感谢你! – Dude
fileExistsAtPath:pathComponent必须fileExistsAtPath:路径 - 那么它运行完美 – Dude
卫生署!我已经编辑了答案,以反映任何绊倒答案的人的更正。 –