2011-06-06 67 views
2

我有一款應用程序利用Core Data SQLITE3在模擬器中完美工作。不過,我不明白如何更新設備上的數據庫,我想這與應用商店中的相同。在設備和應用商店刷新SQLITE3(核心數據)

我更新應用程序中的.txt文件中的數據庫,並創建數據庫,此功能僅用於創建數據庫,並將在最終版本中刪除。我的想法是在模擬器中創建數據庫,鎖定代碼的更新部分,然後用更新的數據庫分發包。

但是,當我在設備上重建我的應用程序時,它仍然具有數據庫中的舊數據。

我一直在環顧四周,但我恐怕不完全明白如何解決這個問題。我確實發現這個線程:Can't refresh iphone sqlite3 database

我非常感謝,如果一些好人可以分享一些光線,並幫助我解決這個問題。

乾杯

回答

0

有複製從包目錄(只讀)數據庫文件,可寫的? (如每個應用程序的文檔目錄?)。

當試圖保存在設備中,你會得到像這樣的sqlite錯誤?

SQLITE_READONLY  8 /* Attempt to write a readonly database */ 

編輯:

所有主束的文件是隻讀的,所以如果你需要修改一個/他們中的一些,你需要將文件是可寫的一個位置複製。假設你已經調用了db mydb.sqlite,這裏有一些將db複製到文檔目錄的代碼(僅當它不存在時)。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    NSString *docPath = [docDirectory stringByAppendingPathComponent:@"mydb.sqlite"]; 
    if (![fm fileExistsAtPath:docPath]) { // file does not exists, copy it 
     NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"sqlite"]; 
     NSError *error = nil; 
     BOOL res = [fm copyItemAtPath:bundlePath toPath:docPath error:&error]; 
     if (!res) { 
      // do something with error 
     } 
    } 
+0

感謝您的回答朱利亞諾,不,我沒有,我恐怕我真的不知道該怎麼做? – PeterK 2011-06-06 09:39:33

0

實際上,在Bundle中使用.db文件 - 這是一個非常糟糕的主意。 每當我使用.db文件時,我正在檢查,如果它已經存在於我的應用程序文檔目錄中,然後我將重寫它。

#define DB_SHOULD_BE_REWRITTEN YES //You should update database and change allready existing db file to file from bundle 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"]; 


    BOOL success = [fileManager fileExistsAtPath:writableDBPath]; 

    if (!success || DB_SHOULD_BE_REWRITTEN) 
    { 
     // The writable database does not exist, so copy the default to the appropriate location. 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"]; 
     success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
     if (!success) { 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
     } 
    } 

    dbPath = writableDBPath; 
相關問題