ldouglas956 ldouglas956 - 1 year ago 97
Swift Question

How can I implement swipe to delete for UITableView containing filtered data from Core Data?

I have two VC with table views, the first showing categories, and the second showing items of selected category (recipes). I am able to get the RecipeTableVC to display filtered data using NSPredicate, but I haven't quite figured out how to delete the recipe from Core Data since the data displayed is a variable containing only the predicated data.

Here is my fetch:

func attemptRecipeFetch() {
let fetchRecipeRequest = NSFetchRequest(entityName: "Recipe")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRecipeRequest.sortDescriptors = [sortDescriptor]

let controller = NSFetchedResultsController(fetchRequest: fetchRecipeRequest, managedObjectContext: ad.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedRecipeController = controller

do {
try self.fetchedRecipeController.performFetch()
let allRecipes = fetchedRecipeController.fetchedObjects as! [Recipe]
recipesOfCategory = allRecipes.filter { NSPredicate(format: "category = %@", selectedCategory!).evaluateWithObject($0) }
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")

So what's populating my table is the recipesOfCategory array.

Here is my attempt to delete so far:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

This crashes and I understand why, but still haven't come up with a solution. Is there a way to implement swipe to delete where it deletes the recipe from Core Data? Am I using the correct methodology to populate the table with filtered data?

Answer Source

I used the following code to 'Swipe to delete from core data' in a table view for an App I recently did. I may work for you.

In your "tableView:commitEditingStyle",

1. set up CoreData access with ...

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext

2. Delete the desired row + incl. from Core Data...

if editingStyle == UITableViewCellEditingStyle.Delete {

context.deleteObject(self.resultsList[indexPath.row]) // Always before as CoreD

            do {
                try context.save()
            } catch {
                print("Error unable to save Deletion")

    } // end IF EditingStyle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download