2011-10-11 124 views
6

我想爲我的應用程序實現多語言支持。所以我創建了Localizing.strings文件和所有這些東西並翻譯了我的界面。到目前爲止好...多語言的多個SQLite數據庫?

現在我想重複我的數據庫,以便有一個* .db的文件爲每一個語言。所以我做了,然後在「本地化」選項卡下的「+」上通過XCode單擊。我現在在我的en.lprojde.lproj文件夾中有一個* .db文件。

我的問題:如果我想將DB-文件複製到應用程序的文件目錄下的* .db文件不可用,當然,因爲它是在*的.lproj文件夾。有沒有任何命令來獲得正確的lproj文件夾?

爲了澄清我的需求: 這不起作用

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

...這樣做:

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

...但我不想添加 「de.lproj」 和「 en.lproj「等手動。有什麼辦法可以動態修復它嗎?

回答

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 
} 

請注意,上面的代碼沒有經過測試,但應該足夠了。您可能需要修改它有點...

+0

真棒答案!非常感謝你! – Dude

+0

fileExistsAtPath:pathComponent必須fileExistsAtPath:路徑 - 那麼它運行完美 – Dude

+0

衛生署!我已經編輯了答案,以反映任何絆倒答案的人的更正。 –

1

事情是這樣的:

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

只是做到以下幾點:

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

,如果你在XX本地化.db文件。 lproj所以正確的數據庫將被採取。