我在我的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