Eric Roller's Development Blog

Value from NSTextField not updated in dictionary (Cocoa binding)

- Posted in macOS by

Two issues today: A simple mini-dialog box with a text field and an ok button. Editing the text field and pressing "ok" did not change the value in the target that is bound to the text field. It turns out, the editing is not finished when we press the button (unless the user presses "tab" or possibly "return"). We can force editing to end through this construct in the action of the ok button:

- (IBAction) ok:(id)sender
    // ask the window to take the focus away from the edit field,
    // thus stop editing and take over the value.
    if ([[sender window] makeFirstResponder:sender])
        [NSApp endSheet:[sender window]
        [[sender window] orderOut:self];

When the value was updated, I got this error in the console:

2006-03-16 23:41:50.940 MyApp[547] ***
-[NSCFString unsignedLongValue]: selector not recognized

This is because the object in the dictionary has been set to a string, not a number:

(gdb) print-object [[data objectForKey:@"teve"] class]
(gdb) print-object [[data objectForKey:@"teve"] class]

... and the string does not support "unsignedLongValue". This could easily be solved by attaching a NSNumberFormatter to the NSTextField, by which means it is also ensured that one only gets legal numbers (e.g. no floating point values and minimum set to 0).