2012-03-19 89 views
0

我在我的iPhone應用程序中使用sqlite數據庫,並且在我的應用程序生命週期中,用戶可能會向它添加一些新記錄。我的問題是,當用戶關閉手機/關閉應用程序時,這些記錄會丟失,應用程序將加載數據庫的原始版本而不添加記錄。objective-c - iPhone - 替換sqlite數據庫的本地副本

我想知道的是,有沒有什麼辦法可以替換存儲在iPhone上的數據庫的本地副本與用戶本質上創建的版本並附加新記錄?如果我實際上無法取代數據庫,那麼最好採取什麼行動來保持新記錄?

感謝,

傑克

編輯:數據庫存儲在文件目錄。

編輯2:

基本上,如果下面的代碼運行,我怎麼會犯下由INSERT語句所做的更改使數據庫的應用程序主要版本更新,而不僅僅是臨時副本?

-(void)insertData{ 

    sqlite3 *database; 
    sqlite3_stmt *statement; 

    //Get the path to the documents directory and append the databaseName 
    AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 
    NSString *databasePath = [appDelegate m_DatabasePath]; 
    NSLog(@"%@", [appDelegate m_DatabasePath]); 
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    { 

     NSString *insertSQL = @"INSERT INTO products (name,category,calories, saturates,fat,fibre,sugar,salt, image) VALUES ('Snickers',' Confectionary','300','55','55','55','55','55', 'http://upload.wikimedia.org/wikipedia/en/8/88/Snickers_wrapped.jpg');"; 
     const char *insert_stmt = [insertSQL UTF8String]; 
     if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL)== SQLITE_OK) 
     { 
      NSLog(@"Here 1"); 
      if(sqlite3_step(statement)==SQLITE_DONE) 
      { 
       //Create a new animal object with the data from the database 
       Product *l_Product = [[Product alloc] initWithName:@"Snickers" category:@"Confectionary" calories:@"300" fat:@"55" saturates:@"50" sugar:@"10" fibre:@"50" salt:@"5" imageURL:@"http://upload.wikimedia.org/wikipedia/en/8/88/Snickers_wrapped.jpg" ]; 

       //Add the animal object to the animals array 
       [appDelegate.m_Products addObject:l_Product]; 

       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Added" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  
       [alert show]; 

      } 
      else 
      { 
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Not Added" message:@"An error has occured" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       [alert show]; 
       alert=nil; 
      } 
     } 
     // Release the compiled statement from memory 
     sqlite3_finalize(statement);  
     sqlite3_close(database); 
    } 
} 
+0

你的數據庫在哪裏?在應用程序捆綁或文檔目錄中?如果它在應用程序包中,則應用程序關閉時將丟失數據。如果它不在那裏,您應該在文檔目錄中創建數據庫的工作副本。 – 2012-03-19 11:39:28

+0

@NoMoreWishes它在文檔目錄 - 對不起,應該提到 - 編輯相應。 – 2012-03-19 11:42:02

+0

發表你的代碼你如何做你的分貝交易。請同時張貼關於如何將數據庫複製到文檔目錄的代碼。 – 2012-03-19 11:42:48

回答

0

如果正在上重新啓動更換的SQLite數據庫那麼它可能是你的代碼做正確的東西。

與其將SQLite數據庫發送到應用程序的資源內部,不如動態創建數據庫。每次啓動應用程序時都會運行一些初始化代碼來創建數據庫。該語句應該是沿着線: -

create TABLE if not exists... 

如果你做到這一點,連接到數據庫正確,那麼你會發現,它可以作爲一個持久性存儲。

不要忘記,您還需要首先創建數據庫(再次,'如果不存在')和任何索引。

0

您可以在應用程序包提供你的數據庫,只需確保在修改(也許是在啓動後的appDidFinishLaunching委託方法)之前的「裸」數據庫複製到文檔目錄。這也將使用戶能夠在未來更新應用程序的同時保持其數據的完整性。

+0

但是在複製之前檢查數據庫是否已經存在,否則它將被覆蓋。 – JeremyP 2012-03-19 11:59:03