Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open/edit a .txt file located in application bundle with NSTextView object

I would like to add an NSTextView object to my app and add an action that opens a .txt file located in the app bundle in the textView. Also - I would like to have the option to edit and save the edited doc without renaming it. So standard save, not save as.

What's the best way to handle this?

like image 839
Paul Avatar asked Dec 13 '22 16:12

Paul


1 Answers

Use NSString to load the file and put it in your text view:

NSTextView *textView; //your NSTextView object
NSError *err = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"EditableFile" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
if(!contents) {
    //handle error
}
[textView setString:contents];

Saving is just the opposite. Get the string and write it to the file:

NSTextView *textView; //your NSTextView object
NSError *err = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"EditableFile" ofType:@"txt"];
NSString *contents = [textView string];
if(![contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err]) {
    //handle error
}
like image 121
ughoavgfhw Avatar answered Jan 19 '23 00:01

ughoavgfhw