2016-11-30 32 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