Search code examples
swiftmacoscocoacore-datansdocument

In a macOS Cocoa Document-Based Application what could be a good implementation strategy for a "New From Template" feature like for example in Logic?


Thanks in advance for your help. I have a good experience on macOS applications, but I am almost new in regard to document-based apps. I am trying with a new project that is document-based and uses CoreData. I would like to implement a "New Document From Template" so that when choosing a certain template, the application creates a New Document with some core data objects created and populated in the document's managed object context. What could be a clean approach to achieve this ? Thanks a lot for your help.


Solution

  • Take a look at NSDocumentController's duplicateDocument(withContentsOf:copying:displayName:) method:

    Creates a new document by reading the contents for the document from another URL, presents its user interface, and returns the document if successful.

    You'll want to call it like this:

    let document = try NSDocumentController.shared.duplicateDocument(
        withContentsOf: templateUrl,
        copying: true,
        displayName: "Untitled")