Refresh NSFetchedResultsController data?

前端 未结 4 708
暗喜
暗喜 2021-02-07 11:48

I can create new managed objects inside my app, in a separate view I have a table view which shows all the objects I have.

When I create a new managed object (in a total

4条回答
  •  有刺的猬
    2021-02-07 12:40

    Updated to latest swift 4.2 and Xcode 10.

    extension MyListController: NSFetchedResultsControllerDelegate {
        func controllerWillChangeContent(_ controller: NSFetchedResultsController) {
            self.tableView.beginUpdates()
        }
    
        func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    
            switch type {
            case .insert:
                self.tableView.insertRows(at: [newIndexPath!], with: .fade)
            case .delete:
                self.tableView.deleteRows(at: [indexPath!], with: .fade)
            case .update:
                self.tableView.reloadRows(at: [indexPath!], with: .fade)
            case .move:
                self.tableView.deleteRows(at: [indexPath!], with: .fade)
                self.tableView.insertRows(at: [indexPath!], with: .fade)
            }
        }
    
    
        func controller(_ controller: 
            NSFetchedResultsController, didChange 
            sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex 
            sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    
            switch (type) {
            case .insert:
                self.tableView.insertSections([sectionIndex], with: .fade)
            case .delete:
                self.tableView.deleteSections([sectionIndex], with: .fade)
            case .move:
                self.tableView.deleteSections([sectionIndex], with: .fade)
                self.tableView.insertSections([sectionIndex], with: .fade)
            case .update:
                self.tableView.reloadSections([sectionIndex], with: .fade)
            }
        }
    
        func controllerDidChangeContent(_ controller: NSFetchedResultsController) {
            self.tableView.endUpdates()
        }
    }
    

提交回复
热议问题