Como bien dice la pregunta, quiero saber como funciona NSFetchedResultsController
y porque usar los métodos del delegate en vez de tableView.reloadData
.
Los estoy usando para armar una TableView
pero no anda para nada bien, al cargar la app no me muestra las entidades en cada cell
y al agregar una nueva entidad, se lagea y ni se muestran las lineas de las celdas.
Dejo el proyecto en dropbox:
https://www.dropbox.com/sh/4fo8h7c4q21t16h/AAAVYOB1rP3zDrq3hwjKG8SWa?dl=0
y un poco del código debajo.
class TableViewController : UITableViewController, AddCourseViewControllerDelegate, NSFetchedResultsControllerDelegate {
var managedObjectContext : NSManagedObjectContext!
//Este objeto se encarga de integrar un fetchRequest con la ViewController.
lazy var fetchedResultController : NSFetchedResultsController = {//Es un closure que devuelve un objeto.
() -> NSFetchedResultsController in
let fetch = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Course", inManagedObjectContext: self.managedObjectContext)
let sort = NSSortDescriptor(key: "author", ascending: true)
fetch.entity = entity
fetch.sortDescriptors = [sort]
let fetchedResult : NSFetchedResultsController = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "author", cacheName: nil)
fetchedResult.delegate = self
return fetchedResult
}()
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultController.performFetch()
} catch {
print("Error")
}
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
//Mark: - NSFetchedResultController delegate methods
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
break;
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
break;
case .Move:
tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
break;
case .Update:
let curso = controller.objectAtIndexPath(indexPath!) as! Course
let cell = tableView.cellForRowAtIndexPath(indexPath!)
cell?.textLabel?.text = curso.title
cell?.detailTextLabel?.text = curso.author
break;
}
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
let set = NSIndexSet(index: sectionIndex)
tableView.insertSections(set, withRowAnimation: .Fade)
break;
case .Delete:
let set = NSIndexSet(index: sectionIndex)
tableView.deleteSections(set, withRowAnimation: .Fade)
break;
default:
break;
}
}
//MARK: - TableView dataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultController.sections![section].numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
let course : Course = (fetchedResultController.fetchedObjects![indexPath.row]) as! Course
cell.textLabel!.text = course.title
cell.detailTextLabel!.text = course.author
return cell
}
private func getFetchedController() -> NSFetchedResultsController {
let fetch = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Course", inManagedObjectContext: self.managedObjectContext)
let sort = NSSortDescriptor(key: "author", ascending: true)
fetch.entity = entity
fetch.sortDescriptors = [sort]
let fetchedResult = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "author", cacheName: nil)
return fetchedResult
}
//MARK: - AddCourseDelegate
func addCourseViewControllerDidSave() {
do {
try managedObjectContext.save()
} catch {
print("Error al guardar el curso.")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func addCourseViewControllerDidCancel(curso : Course) {
managedObjectContext.deleteObject(curso)
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: - Segue way
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "addCourseSegue" {
let nextVc = segue.destinationViewController as! AddCourseViewController
nextVc.delegate = self
let selectedCourse = NSEntityDescription.insertNewObjectForEntityForName("Course", inManagedObjectContext: managedObjectContext) as! Course
nextVc.course = selectedCourse
}
}
}