0

我让用户在 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;

}

4

1 回答 1

1

我将假设您的managedObjectContextpersistentStoreCoordinator方法遵循典型的方法——即在您将它们设置为 nil 之后,再次请求它们将懒惰地重新初始化它们。如果不是这种情况,那么这是第一个问题,即您正在拆除旧的 Core Data 堆栈但没有替换它。

假设这是真的,问题是——正如你在评论中所说——你的应用程序没有尝试获取新数据。如果您希望应用程序显示新数据......您需要让您的应用程序使用获取请求来请求该数据。您的 UI 不会因为您运行上面的方法而自动更新,您需要做一些事情以使其获取新值。

这样做意味着您需要清除从 Core Data 获取的每个对象——每个托管对象以及您可能拥有的任何获取的结果控制器。

于 2016-11-02T21:29:42.480 回答