# Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?

Below is my typical WindowController module for presenting a modal dialog (could be settings, asking username/password, etc) loaded from a XIB. It seems a bit too complex for something like this. Any ideas how this can be done better/with less code?

Never mind that it's asking for a password, it could be anything. What frustrates me most is that I repeat the same pattern in each and every of my XIB-based modal window modules. Which of course means I could define a custom window controller class, but before doing that I need to make sure this is really the best way of doing things.

#import "MyPasswordWindowController.h"

@end

{
NSInteger _dialogCode;
}

- (id)init
{
}

- (void)awakeFromNib
{
[super awakeFromNib];
[self.window center];
}

{
[NSApp stopModalWithCode:_dialogCode];
_dialogCode = 0;
}

- (IBAction)okButtonAction:(NSButton *)sender
{
_dialogCode = 1;
[self.window close];
}

- (IBAction)cancelButtonAction:(NSButton *)sender
{
[self.window close];
}

+ (NSString*)run
{
if (!windowController)
if ([NSApp runModalForWindow:windowController.window])
return nil;
}


The application calls [MyPasswordWindowController run], so from the point of view of the user of this module it looks simple, but not so much when you look inside.

-

Based on Ken Thomases answer given on SO here, here is my revised modal window module. Note that the window should have the system close button disabled, or otherwise you will have to handle windowWillClose, which will lead to having _dialogCode like in my original code above. If, however, OK and Cancel are the only buttons that end the modal dialog, then:

#import "MyPasswordWindowController.h"

@end

- (IBAction)okCancelAction:(NSButton *)sender
{
[NSApp stopModalWithCode:sender.tag]; // the OK button's tag should be 1
[self.window close];
}

+ (NSString*)run
{
if ([NSApp runModalForWindow:windowController.window])
return nil;
}

@end

-