gpt4 book ai didi

swift - 使用 NSFetchedResultsController 从 UITableView 中删除行

转载 作者:行者123 更新时间:2023-11-28 06:57:33 25 4
gpt4 key购买 nike

我正在尝试删除 UITableView 中的一行。该表的数据来自使用 NSFetchedResultsController 的核心数据实体。这是我删除行的代码:

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {

let managedObject:NSManagedObject = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
context?.deleteObject(managedObject)
do {
try context?.save()
} catch {
print("error")
}

favoritesList.reloadData() // UITableView
}
}

应该很简单,但我似乎无法删除一行。请帮助...

最佳答案

这是我删除行的代码部分:

override func tableView(_: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
//creating a delete button

let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete") { (UITableViewRowAction, NSIndexPath) -> Void in

if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {

let restaurantToRemove = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Pub
managedObjectContext.deleteObject(restaurantToRemove)

if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch let nserror as NSError {
NSLog("some error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
deleteAction.backgroundColor = UIColor.redColor()

return [deleteAction]
}

这三个方法:

func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

switch type {
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
default:
tableView.reloadData()
}

pubs = controller.fetchedObjects as! [Pub]
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}

关于swift - 使用 NSFetchedResultsController 从 UITableView 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32980383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com