0
votes

I have an NSTextField bound to a key in the user defaults. When I press enter or leave the field the bound value is properly updated (I have an observer for it). However when I programmatically set the value of the text field the bound value is not updated. The text field however shows the new string I set with:

stockField1.stringValue = [sender representedObject];

(it's set from a menu item handler). Is it necessary to send an additional message to the text field or how else can I make this work?

2

2 Answers

1
votes

Manually triggering key-value binding goes like this:

- (void)symbolSelected: (id)sender
{
    NSTextField *field;
    switch ([sender tag]) {
        case 0:
            field = stockField1;
            break;
        case 1:
            field = stockField2;
            break;
        case 2:
            field = stockField3;
            break;
    }

    field.stringValue = [sender representedObject];
    NSDictionary *bindingInfo = [field infoForBinding: NSValueBinding];
    [[bindingInfo valueForKey: NSObservedObjectKey] setValue: field.stringValue
                                                  forKeyPath: [bindingInfo valueForKey: NSObservedKeyPathKey]];
}
0
votes

Here's the Swift version of Mike's answer, for reference:

guard
    let bindingInfo = self.infoForBinding(NSBindingName.value),
    let observedObject = bindingInfo[NSBindingInfoKey.observedObject] as? NSObject,
    let observedKeyPath = bindingInfo[NSBindingInfoKey.observedKeyPath] as? String else {
        return
}

observedObject.setValue(self.stringValue, forKeyPath: observedKeyPath)