2015-10-06 2 views
0

Я пытаюсь удалить строку в UITableView. Данные для таблицы поступают от основного объекта данных, используя NSFetchedResultsController. Это мой код для удаления строки:Удалить строку из 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

Вот часть моего кода удаления строк:

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