我已经完全没有想法了大约一个星期了。
我有一个包含多个协调器和托管上下文的 CoreData 堆栈,我正在尝试在应用程序中实现注销 功能。
与 CoreData 交互的 TableView 在 TabBarController 中,并且有引导(即注册和登录)NavigationControllers 和 ViewControllers 引导它。
我试图实现的是注销(即放松到初始 ViewController。到目前为止我已经尝试过 - 无济于事:
- 分别重置()每个managedObjectContext
- tableView.beginUpdates()、tableView.endUpdates()、tableView.reloadData()、frc.performFetch() 的所有可能组合
- 删除每个 managedObject 中的每个实体,然后分别重置()每个 managedObjectContext
- 将 tableView、fetchedResultsController 委托(delegate)和数据源设置为 nil,然后在 viewDidLoad() 上设置为 self
- 有一个在注销之前触发的 NSNotification - 删除 CoreData 中的所有内容并保存它,有效地更新和清空表。
- 更多
有没有办法完全重置 CoreData,这样当用户放松到初始 ViewController 并重新运行整个过程时,我不会得到 p>
Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. attempt to insert row 9 into section 0, but there are only 9 rows in section 0 after the update with userInfo (null)
或者在我通过通知清空表格的情况下:
Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. attempt to insert row 9 into section 0, but there are only 0 rows in section 0 after the update with userInfo (null)
如果我注销、关闭应用程序并重新启动,CoreData 工作很好。这种方式没有错误。这让我觉得有一种方法可以完全重置 CoreData(以及任何与其关联的 tableViews、fetchedResultsControllers)或在展开到初始 ViewController 时重置为原始状态。
或者我是否应该只复制 Storyboard并有一组单独的入职 viewController 仅用于注销,这样 CoreData 就不会重新初始化?
有什么想法吗?谢谢。
最佳答案
在 iOS9 及更高版本中,您可以使用 destroyPersistentStore
并可选择添加一个新的
func destroyAllData(storeType : String = NSSQLiteStoreType) throws {
guard let storeURL = persistentStoreCoordinator.persistentStores.last?.url else {
print("Missing store URL")
return
}
try persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: storeType)
// try persistentStoreCoordinator.addPersistentStore(ofType: storeType, configurationName: nil, at: storeURL)
}
关于ios - 完全重置 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53515526/