Created
January 23, 2015 11:04
-
-
Save stevedoyle/dec158bf996f6488d7c3 to your computer and use it in GitHub Desktop.
NSFetchedResultsController Usage Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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