Question

I have an application in which a window should be opened and closed when a checkbox is clicked on or off in a separate window. I can open it, but can't close it. I define a NSWindow in the windowControllerObject and try to close the NSWindow. The relevant code is:

buttonController.h

@interface buttonController : NSWindowController
{
NSButton *showAnswerBox;
infoWindowController *answerWindowController;
}
- (IBAction)showAnswer:(id)sender;
@end

buttonController.m

- (IBAction) showAnswer:(id) sender
{
     if ([sender state] == NSOnState) {
         if (!answerWindowController) {
             answerWindowController = [[infoWindowController alloc] init];
             }
         [answerWindowController showWindow:self];
         }
     else {
        [answerWindowController hideWindow];
     }
}

infoWindowController.h:

@interface infoWindowController : NSWindowController {

IBOutlet NSWindow * infoWindow; 
}
- (id) init;
- (NSWindow *) window; 
- (void) hideWindow;
- (void) tsSetTitle: (NSString *) displayName;

@end

And in infoWindowController.m:

- (NSWindow *) window
{
     return infoWindow;
}

- (void) hideWindow
{
  [[self window] close];
}

The window opens, but it won't close. I've tried several variations, including orderOut on the infoWindowController. I'm sure I'm missing something dumb- what is it?

In IB, the only way I can even get the windows to open is if 'Open at launch' checked- shouldn't I be able to open them programmatically without that?

Was it helpful?

Solution

NSWindowController already defines a window property. You have effectively overridden the getter of that property by implementing your own -window method. The setter, though, is still the inherited version.

So, assuming you have connected the window outlet of the controller to the window in the NIB, the inherited setter is being called. That allows the inherited implementation of -showWindow: to work to show the window. But your -window method will return nil because the inherited setter does not set your infoWindow instance variable.

Get rid of your separate infoWindow property and getter. Just use the inherited window property and its accessors.

OTHER TIPS

If you use NSWindowController it's better to use it's close method:

- (void) hideWindow
{
  [self close];
}

or just:

[answerWindowController close];

But your code is also valid, just make sure that your [answerWindowController window] is not nil. If you load your window from xib you should initialize your window controller with the name of this xib: answerWindowController = [[AnswerWindowControllerClass alloc] initWithWindowNibName:@"YOUR WINDOW XIB NAME"];.

Also check that "Visible at launch" is unchecked for your window (it seems that it doesn't).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top