2010-11-11 49 views
2

我有一個使用Sqlite數據庫來存儲一些數據和一些用戶配置的iPhone應用程序。我遇到的問題是,當我提交應用程序更新時,用戶安裝中的現有數據庫被空數據庫覆蓋,用戶失去了配置。我相信避免這種情況不會太難,但我不知道該怎麼做。如何保持應用程序更新的現有數據庫?

這是我創造的數據庫副本的方法的代碼:

// Creates a writable copy of the bundled default database in the application Documents directory. 
- (void)createEditableCopyOfDatabaseIfNeeded { 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSString *writableDBPath = [self databasePath]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (!success) { 
     // The writable database does not exist, so copy the default to the appropriate location. 
     //NSLog(dbName); 
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName]; 
     success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
     if (!success) { 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
     } 
    } 
} 

這種方法被稱爲形式:

- (BOOL)openDatabase { 
    BOOL success = true; 
    if (!database) { 
     [self createEditableCopyOfDatabaseIfNeeded]; 
     if (sqlite3_open([[self databasePath] UTF8String], &database) != SQLITE_OK) { 
      success = false; 
      // Even though the open failed, call close to properly clean up resources. 
      sqlite3_close(database); 
      NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database)); 
     } 
    } 
    return success; 
} 


- (NSString*)databasePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:dbName]; 
    return path; 
} 

也許我忘了在我的代碼的東西嗎?

有人能幫我解決這個問題嗎?謝謝!

回答

2

如何從你的主束複製SQLite數據庫到應用程序的文件目錄,但只有當它尚不存在?

+0

約瑟夫,謝謝你的回答,我認爲你是對的,那就是我需要的,但是我不能讓它工作。我添加了用於創建數據庫副本的代碼。謝謝。 – Sebastian 2010-11-11 18:24:07

+0

究竟發生了什麼?請注意,BOOL應該是YES或NO,在Objective-C中不是真或假。 – 2010-11-11 19:33:29

+0

強調應該,我認識的大多數人都是這樣使用它。所以如果我通過代碼,我會尋找是的,而不是真的... – 2010-11-11 19:41:34

0

我不太瞭解sqlite數據庫,只是它們是內存數據庫。無法「保留」內存數據庫。你有兩種選擇:

1)找到一種方法來配置你的sqlite使用文件,而不是運行內存中(我不知道這是否可能,我期待但無法快速找到方法)

2)切換到不同的數據庫提供者。如果你的電腦是你的,你可以安裝xampp或者wamp(lamp on linux),包含一個預配置的,可以隨時運行的MySql數據庫。

最後的方法是在退出時臨時存儲sqlite數據,然後在啓動時重新加載它,但這看起來並不是最優的!

如果你並不真的需要一個數據庫,你也可以考慮備用存儲諸如XML或平面文件

+1

iPhone上的sqlite數據庫是擴展名爲.sqlite的文件。您可以將它們存儲在文件系統中。此外,這個問題是iPhone的具體問題,我認爲你一定忽略了這一點。 – 2010-11-11 18:13:26

2

如果您使用的是核心數據,或者使用sqlite,那麼您很可能將數據存儲在「文檔」目錄中。當更新你的應用程序時,這將會消除而不是

相關問題