开发者

How to save/load text files in Objective-C for the iPhone, using 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜