UITableView行在删除后不会被删除

时间:2016-08-08 13:18:18

标签: swift tableview nsfetchedresultscontroller

我遇到了问题,在我删除了tableview行之后,该行未被删除,这是代码,我已经在线跟踪教程,并成功从数据模型,但它不会解除删除的行,除非我放松回到上一个屏幕然后回到这个视图,为什么呢? :

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if (editingStyle == UITableViewCellEditingStyle.Delete) {

        let product = frc.objectAtIndexPath(indexPath) as! Product

        let productName = product.name

        let message = (MCLocalization.sharedInstance.stringForKey("cart_remove_one_item_message",  replacements: ["%s" : productName!]))
        let alert = UIAlertController(title: (MCLocalization.sharedInstance.stringForKey("cart_remove_title")), message: message, preferredStyle: UIAlertControllerStyle.Alert)

        let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
            (_)in

            let managedObject : NSManagedObject = self.frc.objectAtIndexPath(indexPath) as! NSManagedObject
            self.moc.deleteObject(managedObject)
            self.tableView.reloadData()

            do {
                try self.moc.save()  
            } catch {
                print("Failed to save.")
                return
            }
        })

        alert.addAction(OKAction)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(alert, animated: false, completion: nil)
    }  
}

2 个答案:

答案 0 :(得分:2)

您在保存删除之前重新加载表格,因此您将获得仍包含相同数据的重新加载的表格。保存后放置switch($message){ case 'hi': $output = $jsonWelcome; break; case (preg_match('/start/', $message) ? true : false): $output = $jsonHelp; break; }

答案 1 :(得分:0)

您需要从阵列中删除对象,然后在tableView成功后重新加载moc.save()

let managedObject : NSManagedObject = self.frc.objectAtIndexPath(indexPath) as! NSManagedObject
self.moc.deleteObject(managedObject)
do {
   try self.moc.save()

} catch {
    print("Failed to save.")
    return
}

修改 您需要在问题中添加使用NSFetchedResultsController的问题,现在我认为您已使用self.frc.delegate = self设置了委托,然后添加此委托方法也删除了reloadData没有现在需要它。

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

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

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
    switch type {
    case .Insert:
        tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
    case .Delete:
        tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
    default: break
    }
}

有关NSFetchedResultsController检查教程的更多细节,它将对您有所帮助。