【问题标题】:How to edit text saved in CoreData?如何编辑保存在 CoreData 中的文本?
【发布时间】: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 无法正常工作

【问题讨论】:

  • 您应该更新已获取的对象并保存,而不是删除它并添加新对象。

标签: swift core-data


【解决方案1】:

核心数据对象位于内存图中,因此当您编辑对象的某些属性并保存上下文时,该对象已被编辑。

您的问题的一个很好的解决方案是您的所有表的核心数据堆栈中都有您的对象。 您可以在其他控制器中编辑您的对象并订阅您的上下文的 contextWillSave 通知。 这样当你从其他 ViewController 编辑和保存一个笔记时,运行表会通知并刷新数据。

这就是您订阅上下文将保存通知的方式

NotificationCenter.default.addObserver(self, selector: #selector(managedObjectContextWillSave), name: Notification.Name.NSManagedObjectContextWillSave, object: Constants.context)

这就是通知功能的工作方式

@objc
func managedObjectContextWillSave(notification: NSNotification) {
    for object in (notification.object as! NSManagedObjectContext).updatedObjects {
        if let note = object as? Note {
            //Do Something like loading table cell again
        }
    }

}

【讨论】:

  • 嗯,我尝试了不同的方法,但我不明白如何实现功能,你提供了。我应该在哪里定义 managedObjectContextWillSave 函数?分班吗?但是我怎么会从那里打电话给细胞呢?我应该在哪里调用 NotificationCenter.default.addObserver?我有 3 个视图控制器。 1 用于创建笔记(工作正常),1 用于编辑笔记,1 用于在表格中查看它们。我应该在哪一个中编辑 Core Data?
猜你喜欢
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多