Question

My application has a custom format for which it is registered in Info.plist as being an editor and can read and write to that format. It can also read a number of other formats, but cannot write to them. For these formats it is registered in Info.plist as being a viewer.

When I open one of the other formats, everything seems fine, but when I come to save the file my NSDocument is sent the message writeToURL:ofType:error: with the URL of the file I loaded and the type as the UTI of the format I cannot write.

-(NSArray *)writableTypes only returns my custom format's UTI, and -(BOOL)isNativeType: only returns YES for my custom format's UTI.

What I'd like to do is, like other applications that have a native format but can read from other formats, when the user presses Save, the save panel is opened and the user selects a filename in which to save as the native type.

Is this something that NSDocument can do itself, or do I need to check in writeToURL:ofType:error: to see if I need to open the save panel manually?

Was it helpful?

Solution

Answering myself, the solution I found that appears to work is in readFromURL:ofType:error: to reset the NSDocument's fileURL, displayName and fileType for the non-native formats.

- (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)type error:(NSError **)error
{
    // Handle loading as normal

    if (![type isEqualToString:kMyNativeType]) {
        [self setFileType:kMyNativeType];
        [self setFileURL:nil];

        // Without this, all non-native files are displayed as Untitled.
        // This sets the window title as the filename without the extension
        NSArray *filenameComponents = [[url lastPathComponent] componentsSeparatedByString:@"."];
        [self setDisplayName:filenameComponents[0]];
    }

    return YES;
}

I don't know if this is the correct way, but it appears to work for what I want at the moment, and appears to be what is suggested in https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/AdvancedTopics/AdvancedTopics.html#//apple_ref/doc/uid/TP40011179-CH7-SW8

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top