2011-02-14 86 views
2

因此,我可以訪問iPhone/iPod應用程序(Objective-C)中的只讀SQLite數據庫,但是我正在編寫一個新的應用程序,該應用程序將具有可寫的數據庫。顯然,r/w文件必須位於用戶可寫目錄中。我的問題是,應該在應用程序第一次啓動時,是否應該隨應用程序發運一個空數據庫並將其複製到r/w位置,或者創建r/w數據庫?iPhone應用程序數據庫

+1

艦空一個封裝資源,複製到文檔文件夾在第一次運行。比運行(和維護)模式創建腳本便宜。 – 2011-02-14 16:39:12

回答

1

你可以做下去,但它會更容易(且不易出錯)爲您創建一個空數據庫,把它放在你的包,然後做你的AppDelegate.m文件:

- (void)prepareDatabase 
{ 
    //add Database Versioning check to see if the resources database is newer 
    // generally as simple as naming your database with a version on the end 

    NSFileManager *filemanager = [NSFileManager defaultManager]; 
    NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/YOURDATABASE.s3db"]; 
    if(![filemanager fileExistsAtPath:databasePath]) { 
     //Database doesn't exist yet, so we copy it from our resources 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/YOURDATABASE.s3db"]; 
     if([filemanager copyItemAtPath:defaultDBPath toPath:databasePath error:nil]) { 
      NSLog(@"Database Copied from resources");   
     } else { 
      NSLog(@"Database copy FAILED from %@ to %@",defaultDBPath,databasePath); 
     } 
    } 
} 

然後在您的applicationDidFinishLaunching:方法調用此:

[self prepareDatabase]; 
+0

這是正確的(+1)。爲了更加防彈,你可以複製到不同的文件名,然後重命名。這樣,創建空數據庫的最終操作就可以使用原子。 – 2011-02-14 17:50:07

相關問題