2012-08-22 37 views
0

我正在開發一個使用Sqlite3數據庫的應用程序。現在,數據庫是在應用程序包內,但我知道當我在真實世界中測試時,用真正的iPhone來更新數據時會遇到問題。Xcode - 在庫文件夾中保存sqlite3數據庫

1 - 如何在捆綁階段將我的項目數據庫複製到庫文件夾?

2 - 如何訪問此複製的數據庫?現在我的代碼是:

NSFileManager *fileMgr = [NSFileManager defaultManager]; 
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myDatabase.sqlite"]; 
    BOOL success = [fileMgr fileExistsAtPath:dbPath]; 

我需要改變什麼?

3 - 如果我更新應用程序,如何保留此數據庫(使用用戶數據)?

在此先感謝! ;)

回答

1

你必須將數據庫從資源文件夾複製到文件夾

sqlite3 *database; 
BOOL success; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Lists.db"]; 
success = [fileManager fileExistsAtPath:writableDBPath]; 
// The writable database does not exist, so copy the default to the appropriate location. 
if(!success) 
{ 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Lists.db"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
     TFLog(@"Failed moving database... %@",[error localizedDescription]); 
     return; 
    } 
} 

當您在文件更新應用數據庫文件夾將是他們的,你只需要檢查的條件

 success = [fileManager fileExistsAtPath:writableDBPath]; 
if it does not exits new database will be copied their. 
Just keep in mind database structure is same as before. 
+0

您也可以開啓'UIFileSharingEnabled',以便您可以通過iTunes將文件從iPhone複製到iPhone上。 – trojanfoe

+0

謝謝!我正在分析你的代碼,並且我有一些問題:首先,代碼檢查數據庫是否存在於resourcePath中。我應該驗證文檔文件夾嗎?數據庫將在文檔文件夾中安全嗎?語句writableDBPath在哪裏? –

相關問題