Export NSDocument to Mac Application

How to export NSDocument in one format to another NSDocument in another format?

I would like to implement a typical export option in my document-based application. I'm not sure where I should put the format conversion code and what is already provided by Cocoa.

+6
source share
2 answers

All recording parameters in NSDocument receive a string parameter to indicate the type of file to be written. Therefore, in your methods dataOfType:error: or fileWrapperOfType:error: you must implement the conversion code for each type of file that you want to support.

To start the export operation, you can use the saveToURL:ofType:forSaveOperation:completionHandler: method with the desired type and the save operation NSSaveToOperation .

For more information on methods that you can override to support loading and saving document data, see this programming guide .

You can get the available types from the writableTypes class writableTypes or the writableTypesForSaveOperation: instance method, again using NSSaveToOperation .

The types of files you want to support must be declared in your Info.plist file.

+7
source

If your NSDocument subclass supports autosave in place, and all writable types are also readable (as they should), I would recommend using the already provided type conversion workflow where the user should use Duplicate followed by Save.

In this workflow, when a user “Duplicates” a document, it is written / copied to a temporary file (where autosaved files are saved) as an untitled document. When the user closes the document window, the application offers her to save the document or delete it. Since the document does not yet have a permanent URL, an NSSavePanel appears with an additional view that allows the user to select the type of document.

Everything is already provided for in this solution by Cocoa, and you don’t need to do anything to support the special Export functionality, as the user can use Duplicate and then Save. You only need to save the document in all dataOfType:error: types from dataOfType:error: or in fileWrapperOfType:error: according to the typeName argument (as Sven said).

The advantage is that the user needs to select the URL only when she closes the file (and does not want to delete it) - and is compatible with the new workflow in document-based applications, where the “save as” operation has been replaced with a “duplicate” followed by "save."

Note that you also need to make sure that you can duplicate documents from non-record documents (you can achieve this by copying the source file instead of using writeSafelyToURL:ofType:forSaveOperation:error: .

+1
source

All Articles