Skip to content

Instantly share code, notes, and snippets.

@stevedoyle
Created January 23, 2015 11:04
Show Gist options
  • Save stevedoyle/dec158bf996f6488d7c3 to your computer and use it in GitHub Desktop.
Save stevedoyle/dec158bf996f6488d7c3 to your computer and use it in GitHub Desktop.
NSFetchedResultsController Usage Pattern
class GoalsViewController: UITableViewController, NSFetchedResultsControllerDelegate {
...
let managedContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController()
...
func getFetchedResultsController() -> NSFetchedResultsController {
fetchedResultsController = NSFetchedResultsController(fetchRequest: goalFetchRequest(), managedObjectContext: managedContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultsController = getFetchedResultsController()
fetchedResultsController.delegate = self
fetchedResultsController.performFetch(nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return fetchedResultsController.sections![section].numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let goal = fetchedResultsController.objectAtIndexPath(indexPath) as Goal
...
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let managedObject:NSManagedObject = fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
managedContext?.deleteObject(managedObject)
managedContext?.save(nil)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment