我想在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
}
}
应该很简单但我似乎无法删除一行。请帮忙......
答案 0 :(得分:1)
以下是我的代码删除行的部分:
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()
}