views:

225

answers:

2

Hi,

I am creating an application using NSDocument. MyDocument.xib just has an NSTextView in an NSScrollView. When I do a ⌘S to save it, I get an error message ( 'The document “Untitled” could not be saved as “Untitled.rubytext”. '). How can I make my application save it as an RTF file? I mean using NSDocument (I guess dataRepresentationOfType but I am not sure?)

Thanks in advance.

+4  A: 

Apple answered this for you a very long time ago.

Azeem.Butt
Thanks, I'll take a look at it
Time Machine
+1  A: 

I'd like to add that the example implementation of dataForType:error: in the linked page has some either outdated or flatly inaccurate information. Here is the report I sent to Apple:

The example implementation of dataOfType:error: reads:

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
    [textView breakUndoCoalescing];
    NSData *data = [textView dataFromRange:NSMakeRange(0, [[textView textStorage] length])
                             documentAttributes:nil
                             error:outError];
    if (!data && outError) {
        *outError = [NSError errorWithDomain:NSCocoaErrorDomain
                                code:NSFileWriteUnknownError userInfo:nil];
    }
    return data;
}

There are a few problems with this. First, NSTextView does not have a dataFromRange:documentAttributes:error: method. This should be [text dataFromRange…] given the assumed structure of the data specified in the document.

Second, according to the documentation for NSAttributedString, dataFromRange:documentAttributes:error: "requires a document attributes dictionary dict specifying at least the NSDocumentTypeDocumentAttribute to determine the format to write."

So, the example implementation should read at least

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
    [textView breakUndoCoalescing];
    NSData *data = [text dataFromRange:NSMakeRange(0, [[textView textStorage] length])
                             documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:NSPlainTextDocumentType, NSDocumentTypeDocumentAttribute, nil]
                             error:outError];
    if (!data && outError) {
        *outError = [NSError errorWithDomain:NSCocoaErrorDomain
                                code:NSFileWriteUnknownError userInfo:nil];
    }
    return data;
}

or some other appropriate dictionary values for RTF or other text value types.

While it appears that the OP may not have seen that doc at the time of posting, simply linking to the doc doesn't help as much as one might think since the documentation is broken. I discovered this after quite some time banging my own head against the same error as the OP even though I had copied Apple's implementation verbatim.

Hope this helps someone else.

jxpx777