2016-11-30 28 views
0

我有通过UI删除和编辑核心数据实体的功能。虽然这些更改在用户界面中起作用,但在返回视图时不会保留。我相信我错过了一些没有保存发生的事情,但无法解决。这只是一个添加标准保存位置并捕获到删除函数结尾的情况吗?因为这给我解开错误,除非?要么 !使用对实体进行更改时核心数据持久存在的问题

我已经包含了功能的例子中,交换机情况:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { 
    switch (type) { 
    case .insert: 
     if let indexPath = newIndexPath { 
      workoutDesignerTable.insertRows(at: [indexPath], with: .fade) 
     } 
     break; 
    case .delete: 
     if let indexPath = indexPath { 
      workoutDesignerTable.deleteRows(at: [indexPath], with: .fade) 
     } 
     break; 
    case .update: 
     if let indexPath = indexPath, let cell = workoutDesignerTable.cellForRow(at: indexPath) as? RoutineTableViewCell { 
      configure(cell, at: indexPath) 
     } 
     break; 
    default: 
     print("...") 
    } 
} 

删除FUNC

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     // Fetch Exercise 
     let UserExercise = fetchedResultsController.object(at: indexPath) 
     // Delete Exercise 
     UserExercise.managedObjectContext?.delete(UserExercise) 
    } 
} 

回答

1

我认为你需要像这样

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     let UserExercise = fetchedResultsController.managedObjectContext 
     UserExercise.delete(fetchedResultsController.object(at: indexPath)) 
     do { 
       try UserExercise.save() 
     } catch { 
     // Replace this implementation with code to handle the error appropriately. 
     // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     let nserror = error as NSError 
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
     } 
    } 
} 
+0

这个答案似乎工作,谢谢! – infernouk