NSFetchedResultsController with relationship not updating

核能气质少年 提交于 2019-11-26 17:45:29

The NSFetchedResultsController is really only designed to watch one entity at a time. Your setup, while it makes sense, it a bit beyond what the NSFetchedResultsController is currently capable of watching on its own.

My recommendation would be to set up your own watcher. You can base it off the ZSContextWatcher I have set up on GitHub or you can make it even more simple.

Basically you want to watch for NSManagedObjectContextDidSaveNotification postings and then reload your table when one fires that contains your department entity.

I would also recommend filing a rdar with Apple and asking for the NSFetchedResultsController to be improved.

Swift

Because the NSFetchedResultsController is designed for one entity at a time, you have to listen to the NSManagedObjectContextObjectsDidChangeNotification in order to be notified about all entity relationship changes.

Here is an example:

//UITableViewController
//...
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(managedObjectsDidChangeHandler(notification:)), name: .NSManagedObjectContextObjectsDidChange, object: mainManagedContext)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextObjectsDidChange, object: mainManagedContext)
}

@objc fileprivate func managedObjectsDidChangeHandler(notification: NSNotification) {
    tableView.reloadData()
}
//...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!