Skip to content

Instantly share code, notes, and snippets.

@digitalpardoe
Created July 16, 2011 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalpardoe/1086559 to your computer and use it in GitHub Desktop.
Save digitalpardoe/1086559 to your computer and use it in GitHub Desktop.
Rich Text File (RTF) Into NSTextView, Cocoa & Obj-C
- (void)awakeFromNib
{
NSBundle * myMainBundle = [NSBundle mainBundle];
NSString * rtfFilePath = [myMainBundle pathForResource:@"file" ofType:@"rtf"];
[controller_Out_TextView readRTFDFromFile:rtfFilePath];
}
@volomike
Copy link

volomike commented Dec 1, 2015

Oh, sorry to bother you on the Twitters. I found a way to mention something here.

For me, it was easier than creating a nib with a controller in it. Instead, I dragged a Text View widget onto my xib window, and then if you click three times (deep-clicking, I joke), you end up at the NSTextView layer. Then, go up to View > Assistant Editor > Show Assistant Editor, and then select your AppDelegate.m file. (Assuming you did a default Cocoa project with XCode 7, of course, which creates a default AppDelegate.m file.) Then, control-click that NSTextView control in your xib and drag and arrow in your appDelegate.m right underneath your @interface AppDelegate () line. Give it a name like txtRich or whatever. That will create a line automatically that reads:

@property (unsafe_unretained) IBOutlet NSTextView *txtRich;

You've just created what's called an "outlet", which enables us anywhere in AppDelegate.m to speak to self.txtRich. Now, the next thing you do is find some kind of function where you want to trigger this. By default when you create a default Cocoa project, it creates for you an AppDelegate.m that contains a class method: applicationDidFinishLaunching. That's a great place to put our code. The code is really simple. It's:

NSString *sFile = @"/Users/mike/Library/Developer/Xcode/DerivedData/Setup-bjlliqkxyoihomgcoyhdrcdjmgfp/Build/Products/Debug/Setup.app/Contents/Resources/eula.rtfd";
[self.txtRich readRTFDFromFile:sFile];

Now, of course, that's a hard-coded path that I have. You can use your code to get a relative path using your example above:

NSBundle *myBundle = [NSBundle mainBundle];
NSString *sFile= [myBundle pathForResource:@"file" ofType:@"rtfd"];
[self.txtRich readRTFDFromFile:sFile];

(For other viewers reading this, there's no magic to "mainBundle" -- it appears to be a reserved word sort of like defaultCenter is for NSNotificationCenter.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment