如何将文本文件永久保存到iPhone?然后能够在另一个UITextView中再次打开它们吗?
提前致谢。
答案 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;