首页 文章

如何为包含Core Data过滤数据的UITableView实现滑动删除?

提问于
浏览
0

我有两个带有表视图的VC,第一个显示类别,第二个显示所选类别(配方)的项目 . 我能够使用NSPredicate来显示RecipeTableVC以显示过滤数据,但我还没有弄清楚如何从Core Data中删除配方,因为显示的数据是仅包含谓词数据的变量 .

这是我的抓取:

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)")
    }
}

那么填充我的表的是recipesOfCategory数组 .

这是我到目前为止删除的尝试:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        recipesOfCategory.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        ad.managedObjectContext.delete(recipesOfCategory[indexPath.row])
    }
}

这崩溃了,我理解为什么,但仍然没有提出解决方案 . 有没有办法实现滑动删除从Core Data删除配方的位置?我是否使用正确的方法用过滤后的数据填充表格?

2 回答

  • 0

    我使用以下代码在我最近做过的应用程序的表视图中“滑动以从核心数据中删除” . 我可能会为你工作 .

    In your "tableView:commitEditingStyle “,

    1. set up CoreData access with ...

    让appDel:AppDelegate = UIApplication.sharedApplication() . 委托为! 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])//始终在CoreD self.resultsList.removeAtIndex(indexPath.row)之前
    做{
    尝试context.save()
    } catch {
    打印(“错误无法保存删除”)
    }

    } //结束IF EditingStyle

    self.tableView.reloadData()

  • 0

    tableView:commitEditingStyle: 中,您需要 just 从Core Data中删除基础对象,而不是从表视图中删除 . NSFetchedResultsController 委托方法将告诉您何时从表视图中删除它 .

相关问题