Rich Text File (RTF) Into NSTextView, Cocoa & Obj-C

I was searching for an example of how to do this for ages and came up with nothing. All the pros out there will probably say it is easy and give shorter ways of doing this but for noobs and people not in the know I wrote this little snippet. This is especially useful for creating easy to maintain change logs or for adding simple read-me and help files to your application.

First of all you will need to create a NIB file with some sort of controller class in it. In the controller class create an outlet of type ‘NSTextView’, for this example I will call it ‘controller_Out_TextView’. Then generate the files for this controller so they appear in your Xcode project.

Secondly, create a window and add an NSTextView to it from the palette, connect the NSTextView to the outlet in the controller.

You will then need to create your rich text file with the necessary text in it, make sure it is added to your project and will be copied to the application bundle. For this example the text file will be called (rather originally) file.rhtml.

Finally add the following code to the ControllerName.m file between the @implementation and @end, or in your awakeFromNib method, if you already have one.

- (void)awakeFromNib
{
  NSBundle * myMainBundle = [NSBundle mainBundle];
  NSString * rtfFilePath = [myMainBundle pathForResource:@"file" ofType:@"rtf"];
  [controller_Out_TextView readRTFDFromFile:rtfFilePath];
}

Compile and run, hoepfully all of your text will be displayed.

Rich Text File (RTF) Into NSTextView, Cocoa & Obj-C