开发者

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

开发者 https://www.devze.com 2023-02-13 06:35 出处:网络
How开发者_如何学C do you save text files permanently to an iPhone? And then be able to open them again in another UITextView?

How开发者_如何学C do you save text files permanently to an iPhone? And then be able to open them again in another UITextView?

Thanks in advance.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消