NSTextView backed by core data

144 Views Asked by At

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
}
2

There are 2 best solutions below

2
Mundi On

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.

0
Dirk On

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.