Binded NSTextField doesn't update the entity u

2019-08-01 01:27发布

问题:

I have a Core Data project.

Basically I have an NSTableView where I add some entities (using the "add:" selector), double clicking on the TableView opens a new NSWindow where is possible to edit the entity using some NSTextFields. Each text field is binded to an attribute of the entity.

Everything is working fine, except the fact that the entity's attributes are updated only when a textfield lose the focus.

If I write on the first text field and then I move to the second one my entry is saved, but if I write on the first text field and I close the window I lose my changes.

How can I update my core data entity as soon as I write something in the text field? Should I use textDidChange:?

--- UPDATE ---

Unfortunately [context save] doesn't work. If I understand correctly the entity is not modified until the NSTextField resign first responder.

The only working solution for now is something like:

(void)controlTextDidChange:(NSNotification *)aNotification 
{
  NSTextField *tf = [aNotification object];
  [self.window makeFirstResponder:tf];
}

but this is quite inelegant, and in any case I also still need to re-set the cursor at the end of the NSTextField.

回答1:

Setting NSContinuouslyUpdatesValueBindingOption will cause the model to update every time the text field changes, which sets the dirty flag properly and causes the document to save on quit.



回答2:

I think you could use DidEndEditing or TextDidChange, another way of doing this is handeling in the window close event, but I would not recommend it.



回答3:

If you don't have one already, you can set a delegate on the window and use -windowWillClose: or observe the NSWindowWillCloseNotification. You can then call [[notification object] makeFirstResponder:[window initialFirstResponder]] to set the window's first responder to its initial first responder as the window is closing. This will cause the control that is first responder (e.g. NSTextField) to resign the first responder status and the binding will save the changes.