views:

218

answers:

3

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?

+1  A: 

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: on NSDocumentController. 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 which NSDocument subclass to use to open the document.

You could subclass NSDocumentController and override the openDocumentWithContentsOfURL:display:error: method to intercept the file types that should be imported rather than opened. In your NSDocument subclass, write a new initializer with a name like initWithImportedContentsOfURL:type:error: (or something with a better name :-) ) to create a new untitled document and read in the contents of the imported file.

Alex
+1  A: 

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.

sjmulder
+1  A: 

You might try this answer in the Document-Based Applications FAQ.

Peter Hosey