Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultsController.performFetch()
} catch {
print("Error")
}
}
private lazy var fetchedResultsController: NSFetchedResultsController<MyModel> = {
let fetchRequest: NSFetchRequest<Station> = ...
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: container.viewContext, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
return frc
}()
}
extension MyViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let sections = fetchedResultsController.sections {
return sections.count
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let currSection = fetchedResultsController.sections?[section] {
return currSection.numberOfObjects
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
configureCell(cell, at: indexPath)
return cell
}
func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
let item = fetchedResultsController.object(at: indexPath)
cell.textLabel?.text = item.name
// Your custom code to update the cell
}
}
extension MyViewController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo,
atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let indexSet = NSIndexSet(index: sectionIndex) as IndexSet
switch type {
case .insert:
tableView.insertSections(indexSet, with: .fade)
case .delete:
tableView.deleteSections(indexSet, with: .fade)
default:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
guard let i = newIndexPath else { return }
tableView.insertRows(at: [i], with: .fade)
case .delete:
guard let i = indexPath else { return }
tableView.deleteRows(at: [i], with: .fade)
case .update:
guard let i = indexPath, let cell = tableView.cellForRow(at: i) else { return }
configureCell(cell, at: i)
case .move:
if let indexPath = indexPath {
tableView.deleteRows(at: [indexPath], with: .fade)
}
if let newIndexPath = newIndexPath {
tableView.insertRows(at: [newIndexPath], with: .fade)
}
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment