Search code examples
cocoacocoa-bindingsnstextfield

Make NSTextField update its bound value when setting its string value programmatically


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?


Solution

  • 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]];
    }