我让用户在 iOS 设备上通过电子邮件备份和恢复 sqlite 数据库。我成功导出和导入 sqlite 数据库。我的问题是当我想用新文件替换当前的 sqlite 文件时,数据不会自动更新。当我在函数末尾添加一个 exit(0) 时,它会关闭,并且在重新打开应用程序时数据就在那里。这不是一个解决方案,因为它基本上是一个崩溃。这是我用来将一个 sqlite 文件替换为另一个的函数。注意我已经关闭了日志,所以整个数据库是一个 sqlite 文件有人知道在应用程序运行时用另一个 sqlite 文件替换一个 sqlite 文件的正确方法吗?谢谢你。
- (BOOL)resetApplicationModel {
// ----------------------
// This method removes all traces of the Core Data store and then resets the application defaults
// ----------------------
NSError *_error = nil;
NSURL *_storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Database.sqlite"];
NSPersistentStore *_store = [persistentStoreCoordinator persistentStoreForURL:_storeURL];
// Remove the SQL store and the file associated with it
if ([persistentStoreCoordinator removePersistentStore:_store error:&_error]){
[[NSFileManager defaultManager] removeItemAtPath:_storeURL.path error:&_error];
}
if (_error) {
NSLog(@"Failed to remove persistent store: %@", [_error localizedDescription]);
return NO;
}
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
[managedObjectContext release], managedObjectContext = nil;
NSString *applicationDocumentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *originalFile = [applicationDocumentDirectory stringByAppendingPathComponent:@"Database.sqlite"];
NSString *backupDatabaseFolder = [applicationDocumentDirectory stringByAppendingPathComponent:@"Backups"];
NSString *backupFile = [backupDatabaseFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"DatabaseBackup.sqlite"]];
[[NSFileManager defaultManager] copyItemAtPath:backupFile toPath:originalFile error:nil];
// Rebuild the application's managed object context
rootViewController.managedObjectContext = nil;
rootViewController.managedObjectContext = self.managedObjectContext;
return YES;
}