I've written a macOS Document-type app with a storyboard, using the Xcode template, and somewhere along the line the association between the initial app launch and the document has varied from the expected pattern such that none of the NSDocument initializers I expect are called when the app first launches (but are called every new window thereafter).
I've subclassed all four documented NSDocument initializers, as follows:
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
}
}
None of the inits exhibit the debugPrint output when the app launches. The app window is created successfully on launch, with no apparent document association.
However, I notice some really odd behavior I can't explain:
- Although I've seen no init call, autosavesInPlace is called three times after the app starts on some instance of the document
- When I use cmd-N (i.e., File->New and therefore newDocument()) to create a new document, autosavesInPlace is called three more times, and then the document init is executed!
- I never see a call to makeWindowControllers()
My NSDocument subclass is named Simulation. The anomaly seems to be that there's some magic in the initial startup that bypasses Simulation.init, but calls it every document+window creation thereafter.
Here are my questions:
- Why does the initial launch not call Simulation.init()?
- How does autosavesInPlace find an instance of Simulation to call when there's only that initial, seemingly partially constructed window?
autosavesInPlace
is a class method, it is called on the class, not on an instance. Did you implementapplicationShouldOpenUntitledFile
? – WillekeautosavesInPlace
being a class function. Not my day, I guess.. In any event, I had not implementedapplicationShouldOpenUntitledFile
. I did so in the app delegate, and a stub for its partnerapplicationOpenUntitledFile
while I was there, and ran the app. Neither one was ever called - not when I launched the app, and not for cmd-N. – Feldurinit(type:)
. – Willeke