-1

I have a NSTabViewController with a NSTextView in one tab. The text is saved in core data. I save the text when the view disappears.

override func viewWillDisappear()
{
    super.viewWillDisappear()
    self.saveText()
}

But how do I save the text when the document itself closes? At the moment I save on every keystroke, but that is probably too excessive. Is there a better way?

func textDidChange(notification: NSNotification)
{
    self.saveText() //save text after every keystroke => excessive but works
}

edit:

func saveText()
{
    guard let assumedObject = self.representedObject as? NSManagedObject else { return }
    assumedObject.notes = self.textView.string
}
user965972
  • 2,489
  • 2
  • 23
  • 39

2 Answers2

1

NSPersistentDocument takes care of all saving operations, undos etc. This is the whole purpose of this class. There is no need to push anything to Core Data. Just bind your NSTextView value to the Core Data property, that's it.

Better remove all calls to your saveText() function.

Dirk
  • 2,335
  • 24
  • 36
-1

If saveData() works, while saveText() doesn't, maybe you should call saveData() instead.

The proper place to save a text field is in textFieldDidEndEditing:, a text field delegate method.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • saveData is my custom save function. I renamed it here to saveText to make it clearer what it does. But looks like I forgot to do it everywhere. The issue is not saving the text. The issue is avoiding unnecessary work. If the user is typing an entire paragraph, then saving after every keystroke is excessive or not? – user965972 Mar 27 '16 at 08:48
  • I added additional information to indicate where to best save the text field contents. – Mundi Mar 27 '16 at 22:11