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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With