多语言支持:多个SQLite数据库?

6
我想为我的应用程序实现多语言支持。我创建了Localizing.strings文件和其他必要文件,并翻译了我的界面。到此为止一切顺利...
现在,我想复制我的数据库以便为每种语言单独创建一个*.db文件。因此,我创建了这些文件,并在Localization选项卡下通过XCode的“+”按钮添加了它们。现在,我的en.lprojde.lproj文件夹中都有一个*.db文件。
我的问题是:如果我想将这些db文件复制到应用程序的文档目录中,当然不能直接使用*.lproj文件夹中的*.db文件。是否有任何命令可以获取正确的lproj文件夹?
为了澄清我的需求: 这行不通。
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydatabase.db"]

这是它的功能:

[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"de.lproj/mydatabase.db"]

…但我不想手动添加"de.lproj"和"en.lproj"等。有没有办法动态地解决它?

3个回答

3

只需按照以下步骤执行:

NSString *dbpathResource = 
       [[NSBundle mainBundle] pathForResource:@"databaseName" ofType:@"db"];

如果你在xx.lproj中有本地化的.db文件,那么就会使用正确的数据库。

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
}

请注意,上述代码未经过测试但应该足够使用。您可能需要稍微修改它...

fileExistsAtPath:pathComponent 必须是 fileExistsAtPath:path — 然后它就可以完美运行。 - Dude
糟糕!我已经编辑了答案,以反映更正,供其他遇到这个问题的人参考。 - Suhail Patel

1

类似这样:

NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * rootPath = [[NSBundle mainBundle] resourcePath];
NSString * resourcePath = [[NSBundle mainBundle] pathForResource: @"mydatabase" ofType: @"db" inDirectory: rootPath forLocalization: language];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接