objective-c - 防止 window 两次打开...

标签 objective-c cocoa macos

我执行这些行来显示首选项窗口:

-(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 编辑为单例吗?

最佳答案

我的方法是在该操作所属的任何类中创建一个 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

关于objective-c - 防止 window 两次打开...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5991585/

相关文章:

iphone - iPhone 应用程序中的 Google map 导航和方向

objective-c - 子类化 NSCollectionView 后的绘图问题

Cocoa 自动布局和 ScrollView

macos - 使用 bash 脚本在文件中添加多行

java - OSX 上的 Eclipse TPTP 或其他 java 分析解决方案。欢迎提出建议

objective-c - 将 CAGradient mask 层应用于 UITextView

ios - 无法在 Objective-C 中使用 Swift 类

objective-c - 将 NSImage 移动到 NSImageview 中

objective-c - NSScrollView 问题

mysql - 提取两个变量并用sed重写多行