【问题标题】:Reset sqlite db to default values将 sqlite db 重置为默认值
【发布时间】:2012-10-31 09:46:29
【问题描述】:

我正在我的应用程序中编写一个重置函数,它将使用一些预先填充的数据将我的 sqlite 数据库恢复到其原始状态。下面的代码从文档目录中删除数据库并从捆绑包中复制数据库,但数据仍然出现在旧数据库中?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"];

 if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ 

    [[NSFileManager defaultManager]      removeItemAtPath:filePath error:nil]; 

}

BOOL success; 
NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error;

NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; 
 NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; 

 success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 

if (!success) {

    NSAssert1(0, @"Failed to create writable   database file with message '%@'.", [error localizedDescription]); 
}

【问题讨论】:

    标签: ios iphone sqlite reset nsfilemanager


    【解决方案1】:

    我在我的一个应用程序中执行此操作。我在我的应用程序包中保留了一个预构建的数据库文件。该数据库包含所有表格和示例数据。

    当我需要重置用户的数据库时,我将其关闭,然后使用捆绑包中的干净副本覆盖数据库。

    【讨论】:

      【解决方案2】:

      只需关闭现有的 sqlite 数据库,然后再次从包中复制它,覆盖现有的数据库。它的完成方式与您第一次复制时的方式基本相同。

      【讨论】:

      • 谢谢,我在关闭数据库后尝试以下操作: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; }
      • BOOL 成功; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *错误; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MoneyMonthly.sqlite"];成功 = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if (!success) { NSAssert1(0, @"无法创建可写的数据库文件,消息为 '%@'。", [错误本地化描述]); }
      • 而且,它有效吗?如果没有,请告诉我们错误消息是什么,我们会尽力提供帮助。此外,如果您将代码添加到您的问题并将其格式化为代码,它将更加更具可读性并且每个人都会看到它并能够提供帮助。跨度>
      • 抱歉,我确实尝试过格式化它。我没有收到任何错误,但它仍然包含我从原始数据库版本输入的一些数据。
      • 点击问题下方的“编辑”,将代码复制并粘贴到您的原始问题中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 2011-04-06
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      相关资源
      最近更新 更多