There's a file type my application import but not save. I've added an entry to the document types and set it to read-only, but that doesn't yield the import behaviour that I'm looking for. Instead, my app will just open the file and when I save the original file is overwritten in my own file format.
How to set up my document or document types to make it so that a new document is created with the data from the original document, instead of the original being opened?
Alex, thanks for your answer, but I found a way that I like a bit more:
This way it's still possible to use the document system provided by Cocoa instead fo rolling my own.
I've also documented the solution here: http://www.cocoadev.com/index.pl?CFBundleTypeRole a bit down the page.
1. Declare the file types as Document Types
Within your Xcode project, add a Document Type for all the file formats your application supports. Set the Role of each type according to your application's abilities:
Set the Class to the document type you want to handle each file type. One document class can handle multiple file types.
In the example below, there are three file types declared: font-pestle, otf, and ttf. The first, font-pestle, is the native format of the application. This type has the role Editor.
The remaining two formats, otf and ttf, can be imported but not written by the application; thus they are marked as Viewer.
2. Additional file types in your NSDocument subclass
With the Document Types added, the application will automatically allow users to open files of the specified types.
You need to add file type handling code to your document class. In the ideal case, add the branching code to the
readFromData:ofType:error:
method:The
self.fileURL = nil;
is important. By setting fileURL to nil, you are saying the document is not associated with any on-disk file and should be treated as a new document.To allow auto-saving, implement the NSDocument method
autosavingFileType
to return the primary file type.I don't believe that import functionality is supported by default in Cocoa. When the user clicks the Open button in the open panel, the framework calls
openDocumentWithContentsOfURL:display:error:
onNSDocumentController
. This is where the document system figures out what type of file you're opening and consults with the Info.plist file to figure out whichNSDocument
subclass to use to open the document.You could subclass
NSDocumentController
and override theopenDocumentWithContentsOfURL:display:error:
method to intercept the file types that should be imported rather than opened. In yourNSDocument
subclass, write a new initializer with a name likeinitWithImportedContentsOfURL:type:error:
(or something with a better name :-) ) to create a new untitled document and read in the contents of the imported file.