【问题标题】:Cocoa document based app, NSWindowController subclass as "main window"基于 Cocoa 文档的应用程序,NSWindowController 子类作为“主窗口”
【发布时间】:2014-08-19 13:46:39
【问题描述】:

我有一个基于 Cocoa 文档的应用程序。我希望“主窗口”由我的子类NSWindowController 管理。我已经创建了子类并在同名的 .xib 文件中布置了它的接口。我最终想要的行为与 NSDocument 管理窗口一样,而是由 NSWindowController 管理。

首先,我该怎么做?其次,在使用这种方法时我需要考虑什么特别的事情,例如如何处理打开和保存?

【问题讨论】:

  • 即使在基于文档的应用程序中,窗口也将始终由NSWindowController 类(或子类)管理。 NSDocumentNSWindowController 之间存在一对多的关系。
  • 好的,但是我怎样才能将NSWindowController 对象改为我的子类的一个实例呢?
  • 你必须用谷歌搜索检查,但我相信你会覆盖[NSDocument makeWindowControllers]

标签: macos nsdocument nswindowcontroller


【解决方案1】:
  1. 用你自己的 windowController 实例覆盖 makeWindowControllers

    //Lazy instantiation of window controller
    - (WindowController *)controller {
      if (!_controller) {
          _controller = [[WindowController alloc] initWithWindowNibName:@"Document"];
      }
    
      return _controller;
    }
    
    - (void)makeWindowControllers {
      [self addWindowController:self.controller];
    }
    
  2. 评论 windowNibName & windowControllerDidLoadNib:aController 方法

    //- (NSString *)windowNibName
    //{
    //  // Override returning the nib file name of the document
    //  // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    //  return @"Document";
    //}
    
    //- (void)windowControllerDidLoadNib:(NSWindowController *)aController
    //{
    //  [super windowControllerDidLoadNib:aController];
    //  // Add any code here that needs to be executed once the windowController has loaded the document's window.
    //}
    
  3. 将 Document.xib 文件所有者类从 NSDocument 更改为您的 WindowController

您可以从您的 WindowController 向您的文档类发送消息(调用方法)。

还要确保你理解这个图表:

【讨论】:

  • 关于那个图...一个 NSDocument 可以有多个 NSWindowController,每个都有一个 NSWindow。我错了吗?
  • 就我而言,我的自定义 MyDocument 有数十个网点。在我看来,如果我想拥有一个自定义的 NSWindowController,我必须将所有这些插座移动到我的自定义窗口控制器,并重构所有代码?那太疯狂了
  • 这是因为您拥有现有的应用程序,并且您的架构起步较晚。你必须做很多重构。如果您想拥有自定义 nswindowcontroller,则不存在其他解决方案
  • 谢谢我明白了。我认为这是苹果糟糕的设计。当您有一个复杂的应用程序时,您根本无法预料到在 2 年后的开发中您将需要一个自定义的 nswindowcontroller。最终,我们找到了我们想要实现的解决方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
相关资源
最近更新 更多