Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do you save text files permanently to an iPhone? And then be able to open them again in another UITextView?

Thanks in advance.

like image 541
ayve Avatar asked Dec 04 '22 23:12

ayve


1 Answers

To write a 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 text property of UITextView to set and get NSString.

NSString *str = myTextView.text;
myAnotherTextView.text = str;
like image 64
taskinoor Avatar answered Mar 22 '23 23:03

taskinoor