Documents文件夹是存储应用程序所用文件的地方,下面这个例子是向Documents文件夹添加一个txt文件并写入内容,然后读取这个文件的内容到屏幕上(在下面那幅图中,先在上面那个文本筐中输入内容,然后点击“点击保存到Documents文件夹中”按钮,这样就会将输入在文本筐中的内容保存到文件中,当点击“点击读取保存的文件内容”按钮时就会将文件中的内容显示在下面的文本标签中):
1.新建一个View-based Application项目,在Interface Builder中添加一些视图控件,如下图所示:
2.在.h文件中添加如下代码(控件和成员变量之间的连接就省了):
#import <UIKit/UIKit.h> @interface FileToDocuments : UIViewController { IBOutlet UITextField *mytextfield; IBOutlet UILabel *mylabel; NSString *filepathDocu;//文件路径 IBOutlet UIScrollView *myscrollview; } @property(nonatomic,retain)UITextField *mytextfield; @property(nonatomic,retain)UILabel *mylabel; @property(nonatomic,retain) UIScrollView *myscrollview; @property(nonatomic,retain)NSString *filepathDocu; -(IBAction)writeToFile;//将字符串写入文件 -(IBAction)readFromFile;//读取文件内容 -(NSString *)getDocumentsPath;//获取Documents文件所在的目录 -(IBAction)tuichujianpan:(id)sender; @end
3.在.m文件中第一如下几个方法,每个方法上面都有说明,这里就不重复了:
//获取Documents文件夹路径 -(NSString *)getDocumentsPath{ NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [path objectAtIndex:0]; return documentsDir; //获取临时文件tmp路径的代码:return NSTemporaryDirectory(); }
//将输入到文本筐中的字符保存到文件中,这个方法是界面上“点击保存到Documents文件夹中”按钮的点击事件 -(IBAction) writeToFile{ NSMutableArray *array = [[NSMutableArray alloc]init]; [array addObject:mytextfield.text]; [array writeToFile:self.filepathDocu atomically:YES]; [array release]; }
//读取所保存的文件到lable中,这个方法是界面上“点击读取保存的文件内容”按钮的点击事件 -(IBAction)readFromFile{ if ([[NSFileManager defaultManager] fileExistsAtPath:self.filepathDocu]) { NSArray *array = [[NSArray alloc]initWithContentsOfFile:self.filepathDocu]; NSString *data = [NSString stringWithFormat:@"%@",[array objectAtIndex:0]]; mylabel.text = data; [array release]; } }
4.在viewDidLoad方法里面为文件路径赋值和设置scrollview的大小:
- (void)viewDidLoad { //成员变量在用的时候一定要写上self,否则有时候会出错 self.filepathDocu = [[self getDocumentsPath] stringByAppendingPathComponent:@"data.txt"]; myscrollview.frame = CGRectMake(0, 0, 320, 460); [myscrollview setContentSize:CGSizeMake(320,599)]; [super viewDidLoad]; // Do any additional setup after loading the view from its nib. }
5.当点击文本筐后键盘就会弹出来,但是不作处理的话键盘是不会消失的,这样给用户的体验不好,所以当我们点击键盘的return按钮之后就要隐藏键盘,这里定义一个方法,这个方法的作用是将当前控件移除其First Responder状态,这样键盘就会隐藏了,不过需要将界面中Text Field视图的Did End on Exit事件与这个方法相连:
//退出键盘 -(IBAction)tuichujianpan:(id)sender{ [sender resignFirstResponder]; }