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?
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.
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:
- (BOOL)readFromData:(NSData*)someData ofType:(NSString*)typeName error:(NSError**)outError
{
if ([NSWorkspace.sharedWorkspace type:@"eu.miln.font-pestle" conformsToType:typeName] == YES)
{
// read native format
}
else if ([NSWorkspace.sharedWorkspace type:@"public.opentype-font" conformsToType:typeName] == YES)
{
// read import only format
// disassociate document from file; makes document "untitled"
self.fileURL = nil;
// associate with primary file type
self.fileType = @"eu.miln.font-pestle";
}
else // ...
}
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.
Alex, thanks for your answer, but I found a way that I like a bit more:
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName
error:(NSError **)outError
{
*outError = nil;
if ([typeName isEqualToString:@"SomeReadOnlyType"])
{
// .. (load data here)
[self setFileURL:nil];
return result;
}
else
{
// .. (do whatever you do for other documents here)
}
}
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.
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