Search code examples
cocoacocoa-bindings

OK button behaves differently when mouse-clicked


I have a modal sheet with an NSTextField control, an OK button and a Cancel push button. The OK button is bound to an action method called theSheetOK in my controller class. I also bound NSTextField control to an NSString member named foo in my controller (File's Owner) and I use key-value bindings to read the text value user entered (i.e. model-key path of text field in the bindings inspector is set to foo).

All works fine if the text is entered and user hits the OK button via keyboard. When I trace the value of foo with NSLog in theSheetOK handler I see the value I just typed in the text field.

However when I clicked the OK button with mouse, the value of foo is logged as empty, also as soon as I click the OK button, the text field control grabs the focus and the text I typed appears selected. Any ideas what went wrong?

@interface MyController : NSWindowController {
@private
NSString *foo;
}
@property (copy, readwrite)NSString* foo;
-(IBAction) theSheetOK:(id)sender;
-(IBAction) theSheetCancel:(id)sender;
@end
...
#import "MyController.h"
@implementation MyController
@synthesize foo;

-(IBAction) theSheetOK:(id)sender
{
  NSLog(@"theSheetOK");
  NSLog(@"foo= %@", foo);
  ...
  NSWindow* theSheet = [self window];
  [NSApp endSheet:theSheet returnCode: NSOKButton];
  [theSheet orderOut:nil];

Solution

  • Sometimes you need to press enter to "confirm a change" to cocoa bindings. I'm not sure, but it's possible that when you hit enter both the change and button action are performed.

    If that's the case, select your NSTextField and mark the option "Continuously Updates Value" so things get synced properly.

    enter image description here