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

I would like to add an NSTextView object to my application and add an action that opens the .txt file located in the application bundle in the text element. In addition, I would like to be able to edit and save the edited document without renaming it. Thus, standard saving, not saving as.

What is the best way to handle this?

+4
source share
1 answer

Use NSString to load the file and put it in a 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]; 

Conservation is just the opposite. Get the string and write it to a 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 } 
+12
source

Source: https://habr.com/ru/post/1336226/


All Articles