Search code examples
xcodemacoscocoadocumentrtf

Error opening a RTF File created through Xcode


I'm trying to create an rtf file from a string. The rtf file is created successfully but when i try to open the file the following alert appears (something like):

It was not possible to open the document "aa.rtf".

I have the following code on my project:

NSString* lol = @"sasasafagagsadfsada";
    NSSavePanel *panel = [NSSavePanel savePanel];

    [panel setAllowedFileTypes:[NSArray arrayWithObject:@"rtf"]];
    if ([panel runModal] == NSOKButton){
        [lol writeToURL:[panel URL] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    }


What's wrong?
Thanks!


Solution

  • You should use NSAttributedString instead of NSString for rich text. Format the text however you like, then write to an RTF with:

    NSAttributedString *str = ...;
    NSData *rtfData = [str RTFFromRange:NSMakeRange(0, [str length]) documentAttributes:nil];
    [rtfData writeToFile:destinationPath atomically:YES];
    

    To learn how to create and manipulate an attributed string, see Apple's Attributed String Programming Guide.