我执行这些行来显示首选项窗口:
-(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];
}
但是当用户第二次点击偏好设置按钮(且偏好设置窗口仍处于打开状态)时,它将打开首选项窗口的另一个实例。
如何在不破坏控制变量的情况下防止这种情况发生?我应该将PreferencesWindowController编辑为单身吗?
答案 0 :(得分:1)
我的方法是在此操作所属的任何类中创建PreferencesWindowController ivar:
@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