How do you export a NSDocument
in one format into another NSDocument
in another format?
I would like to implement the typical Export option in my document-based app. I'm not sure where I should put the format conversion code, and what is already provided by Cocoa.
All the writing options in NSDocument
get a string parameter to specify the type of file that should be written. So in your dataOfType:error:
or fileWrapperOfType:error:
methods you should implement the conversion code for each file type you want to support.
To start your export operation you can use the method saveToURL:ofType:forSaveOperation:completionHandler:
with the desired type and a save operation of NSSaveToOperation
.
For more information on the methods you can override to support loading and saving document data take a look at this programming guide.
You can get the available types from the class method writableTypes
or the instance method writableTypesForSaveOperation:
, again with NSSaveToOperation
.
The file types you want to support need to be declared in your Info.plist file.
If your NSDocument subclass supports in-place autosaving, and all writable types are also readable (as they should be), I would recommend to use the already provided type-conversion workflow, where the user should use "Duplicate" followed by "Save".
In this workflow, when the user "Duplicate" the document, it's written/copied to a temporary file (where autosaved files are saved) as an untitled document. When the user closes the document window, the app suggests her to save the document or delete it. Since the document has no permanent URL yet, an NSSavePanel will appear with an accessory view that lets the user to select the document type.
In this solution everything is already provided by Cocoa and you don't have to do anything to support a special "Export" functionality as the user can use "Duplicate" followed by "Save".
You only have to be able to save your document to all writable types from dataOfType:error:
or in fileWrapperOfType:error:
according to the typeName
argument (as Sven said).
The advantage here is that the user has to choose the URL only when she closes the file (and chooses not to delete it) - and is compatible with the new workflow in document-based apps where the "save as" operation has been replaced by "duplicate" followed by "save".
Note that you also have to make sure that you can duplicate documents of non-writable documents (you can achieve that by copying the original file instead of using writeSafelyToURL:ofType:forSaveOperation:error:
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With