How to save / load text files in Objective-C for iPhone using UITextView?

How to save text files on iPhone? And then can you reopen them in another UITextView?

Thanks in advance.

+4
source share
1 answer

To write NSString to a file:

  NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString * documentsDirectory = [paths objectAtIndex: 0];
 NSString * filePath = [documentsDirectory stringByAppendingPathComponent: @ "file.txt"];

 NSString * str = @ "hello world";

 [str writeToFile: filePath atomically: TRUE encoding: NSUTF8StringEncoding error: NULL];

To load NSString from a file:

  NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString * documentsDirectory = [paths objectAtIndex: 0];
 NSString * filePath = [documentsDirectory stringByAppendingPathComponent: @ "file.txt"];
 NSString * str = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: NULL];

And use the text property of UITextView to set and get an NSString.

  NSString * str = myTextView.text;
 myAnotherTextView.text = str;
+15
source

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


All Articles