[英]How to update CoreData data using Swift
在我的場景中,我將 popupVC 文本字段title
和descript
值存儲到 CoreData 中。 一次,將數據存儲到 CoreData 中,然后將數據提取到 UITableView 中。 我在editActionsForRowAt
有編輯按鈕的每個 Tableview 單元格。 有一次,用戶單擊了我正在傳遞EditpopupVC.task = self.userData[indexPath.row]
的編輯按鈕。 在 EditpopupVC 中,我收到類似var task: NSManagedObject? = nil
var task: NSManagedObject? = nil
。 現在,如果用戶單擊更新按鈕,則修改數據后,我將調用func update(title: String, descript: String) { }
以獲取傳遞的特定值更新。
編輯按鈕單擊以將數據從 ListViewController 傳遞到 EditpopupVC
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
let task = self.userData[indexPath.row]
let EditpopupVC = self.storyboard?.instantiateViewController(withIdentifier: "editviewcontroller") as! EditViewController
EditpopupVC.titlename = "Edit"
EditpopupVC.task = self.userData[indexPath.row]
EditpopupVC.modalTransitionStyle = .crossDissolve
EditpopupVC.modalPresentationStyle = .overFullScreen
self.present(EditpopupVC, animated: true, completion: nil)
})
return [editAction]
}
一旦用戶修改文本數據然后更新按鈕點擊調用更新功能
update(title: Titletextfield.text ?? "Empty", descript: Descriptiontextview.text)
我在下面使用的 CoreData 更新功能
func update(title: String, descript: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
task.title = title
task.descript = descript
do {
try managedObjectContext.save()
} catch {
print("Could not save. \(error)")
}
}
EditpopupVC.task = self.userData[indexPath.row]
這一行有助於將數據數組傳遞給EditpopupVC
。
Core Data 對象是引用類型,您不需要將對象分配回數組。
發生崩潰是因為您沒有在popupVC
設置tasks
,因此它保持為空並引發超出范圍的異常。
在主控制器中聲明具有更具體類型的updateTitles
var updateTitles = [Myrecord]()
在popupVC
刪除tasks
,將tasks
聲明為
var task : Myrecord!
並將update
替換為
func update(title: String, descript: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
task.title = title
task.descript = descript
do {
try managedObjectContext.save()
self.dismiss(animated: true, completion: nil)
} catch {
print("Could not save. \(error)")
}
}
不需要索引路徑。
當控制器消失時,重新加載表格視圖。
邊注:
強制解包AppDelegate
很好。 沒有AppDelegate
,應用程序甚至不會啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.