【问题标题】:Delete row from UITableView using NSFetchedResultsController使用 NSFetchedResultsController 从 UITableView 中删除行
【发布时间】:2015-10-06 21:51:13
【问题描述】:

我正在尝试删除 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
    }
} 

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

【问题讨论】:

    标签: swift uitableview ios9 nsfetchedresultscontroller


    【解决方案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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2012-06-05
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多