2012-03-19 40 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