从故事板启动的初始应用程序无法调用NSDocument init

Fel*_*dur 3 macos init storyboard nsdocument swift

我已经使用Xcode模板编写了一个带有故事板的macOS文档类型的应用程序,并且在某个地方,初始应用程序启动和文档之间的关联与预期的模式不同,因此我没有期望的NSDocument初始化程序是应用程序首次启动时调用(但此后每个新窗口调用).

我已经将所有四个记录的NSDocument初始化器子类化,如下所示:

public class Simulation: NSDocument {

        override init() {
        debugPrint("--------------------\(#file)->\(#function) called")
        super.init()
    }

    init(contentsOf: URL, ofType: String) throws {
        debugPrint("--------------------\(#file)->\(#function) called")
        fatalError()
    }

    init(for: URL?, withContentsOf: URL, ofType: String) throws {
        debugPrint("--------------------\(#file)->\(#function) called")
        fatalError()
    }
    convenience init(type: String) throws {
        debugPrint("--------------------\(#file)->\(#function) called, type: \(type)")
        self.init()
    }

    public override class func autosavesInPlace() -> Bool {
        debugPrint("--------------------\(#file)->\(#function) called")
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序启动时,没有任何内容显示debugPrint输出.应用程序窗口在启动时成功创建,没有明显的文档关联.

但是,我注意到一些我无法解释的奇怪行为:

  1. 虽然我没有看到init调用,但是在应用程序启动文档的某个实例后,会调用autosavesInPlace三次
  2. 当我使用cmd-N(即File-> New,因此newDocument())创建一个新文档时,再调用autosavesInPlace三次,然后执行文档init!
  3. 我从来没有看到makeWindowControllers()的调用

我的NSDocument子类名为Simulation.异常似乎是初始启动中有一些魔法绕过Simulation.init,但之后调用它的每个文档+窗口创建.

这是我的问题:

  1. 为什么初始启动不会调用Simulation.init()?
  2. 当只有那个看似部分构造的初始窗口时,autosavesInPlace如何找到要调用的Simulation实例?

Mat*_*ues 7

在你的故事板,要确保你的窗口控制器及其内容的浏览器有Is Initial Controller泛滥,Presentation设置为Multiple在属性检查器.

窗口控制器属性检查器图像

查看控制器属性检查器图像

Is Initial Controller检查会导致应用程序前,任何实例化一个窗口控制器NSDocument/ NSDocumentController"神奇"的发生.Presentation: Multiple应该选择一致性,尽管它可能没有什么区别.

另外,请确保您的文档类型已正确设置Info.plist,尤其是NSDocumentClass密钥(应包含$(PRODUCT_MODULE_NAME).Simulation).

我相信你的问题autosavesInPlace已在评论中得到解答......