tamasgal
tamasgal

Reputation: 26259

Prevent window from opening twice…

I execute these lines to show the preferences window:

-(IBAction)showPreferences:(id)sender {
    PreferencesWindowController *preferencesWindowController = [[PreferencesWindowController alloc] init];
    NSNib *preferencesNib = [[NSNib alloc] initWithNibNamed:@"PreferencesWindow" bundle:nil];
    [preferencesNib instantiateNibWithOwner:preferencesWindowController topLevelObjects:nil];
    [NSApp activateIgnoringOtherApps:YES];
    [[preferencesWindowController window] makeKeyAndOrderFront:nil]; 
    [preferencesNib release];
}

But when the user clicks a second time on the preferences button (and the preferences window is still open) it will open up another instance of the preferences window.

How should I prevent this without hacking around with control variables? Should I edit my PreferencesWindowController to be a singleton?

Upvotes: 1

Views: 226

Answers (1)

sbooth
sbooth

Reputation: 16966

My approach would be to make a PreferencesWindowController ivar in whatever class this action belongs to:

@interface foo : NSObject
{
@private
  PreferencesWindowController *_pwc;
}
- (IBAction) showPreferencesWindow:(id)sender;
@end

@implementation foo

- (void) dealloc
{
  [_pwc release], _pwc = nil;
  [super dealloc];
}

- (IBAction) showPreferencesWindow:(id)sender
{
  if(nil == _pwc)
    _pwc = [[PreferencesWindowController alloc] initWithWindowNibName:@"PreferencesWindow"];
  [_pwc showWindow:sender];
}

@end

Upvotes: 1

Related Questions