如何使用UITextView在Objective-C中为iPhone保存/加载文本文件?

时间:2011-02-24 06:04:34

标签: iphone objective-c uitextview

如何将文本文件永久保存到iPhone?然后能够在另一个UITextView中再次打开它们吗?

提前致谢。

1 个答案:

答案 0 :(得分:15)

将NSString写入文件:

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

从文件加载NSString:

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

使用UITextView的text属性来设置和获取NSString。

NSString *str = myTextView.text;
myAnotherTextView.text = str;