Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export NSDocument in Mac app

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.

like image 707
hpique Avatar asked Jan 16 '13 13:01

hpique


2 Answers

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.

like image 136
Sven Avatar answered Oct 07 '22 02:10

Sven


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:).

like image 45
Yoav Avatar answered Oct 07 '22 01:10

Yoav