将SQLite DB重置为默认值



我在我的应用中编写一个重置功能,该功能将使用一些预填充的数据将我的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]); 
}

我在我的一个应用程序中这样做。我将一个预构建的数据库文件保留在我的应用程序包中。该数据库具有所有表和示例数据。

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

只需关闭您现有的SQLITE数据库,然后再次从捆绑包中复制它,从而超过了现有数据库。这基本上就像您第一次复制时一样。

最新更新