【发布时间】:2019-05-13 14:49:34
【问题描述】:
我将 CoreData 添加到我的 Notes 应用程序中。它保存数据,删除它等。现在我坚持编辑已经存在的笔记。
好吧,我试图删除上一个项目并保存新项目,但我现在如何在 tableView 中执行此操作,您可以在其中“notes.remove(at: indexPath.row)”,但我不知道该怎么做它在另一个 vieController 中。另外,我试图用“过滤”删除对象,但它也不起作用
此函数从 CoreData 加载笔记:
func getNotes(with request: NSFetchRequest<Note> = Note.fetchRequest()) {
do {
notes = try Constants.context.fetch(request)
} catch {
print("Loading error \(error)")
}
tableView.reloadData()
}
这个救了它:
func saveNote() {
do {
try Constants.context.save()
} catch {
print(error.localizedDescription)
}
}
我正在尝试添加编辑功能:
func editNote() {
let editedNote = Note(context: Constants.context)
editedNote.text = noteDetailOutlet.text
dataManager.saveNote()
navigationController?.popViewController(animated: true)
callback?()
}
这是我对 vc 执行 segue 的,它会进行更改:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "NoteDetailsViewController") as! NoteDetailsViewController
let note = notes[indexPath.row]
vc.passedNote = note.text ?? "Empty note"
vc.callback = { [weak self] in
if Constants.context.hasChanges {
self?.notes.remove(at: indexPath.row)
}
self?.getNotes()
}
Constants.context.hasChanges 无法正常工作
【问题讨论】:
-
您应该更新已获取的对象并保存,而不是删除它并添加新对象。