我在我的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);
}
}
你的數據庫在哪裏?在應用程序捆綁或文檔目錄中?如果它在應用程序包中,則應用程序關閉時將丟失數據。如果它不在那裏,您應該在文檔目錄中創建數據庫的工作副本。 – 2012-03-19 11:39:28
@NoMoreWishes它在文檔目錄 - 對不起,應該提到 - 編輯相應。 – 2012-03-19 11:42:02
發表你的代碼你如何做你的分貝交易。請同時張貼關於如何將數據庫複製到文檔目錄的代碼。 – 2012-03-19 11:42:48