phoenix13

导航

 

1.每个ios程序都有一个这样的目录:

 

2.获取Documents目录:

    NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[path objectAtIndex:0];
NSLog(@"%@",documentsDirectory);

在末尾附加另一个字符串来创建文件名

NSString *fname=[documentsDirectory stringByAppendingPathComponent:@"newFile.txt"];//完整路径

 

3.获取tmp目录:

NSString *temPath=NSTemporaryDirectory();


4. 把2个textField的数据保存,下次打开时加载。

-(NSString *)dataFilePath//返回文件路径
{
NSString *fileName=@"userdata.txt";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[path objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:fileName];
}

文件操作

-(IBAction)saveToFile
{
NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:text1.text];
[array addObject:text2.text];
[array writeToFile:[self dataFilePath] atomically:YES];
}

-(IBAction)loadFromFile
{
NSString *filePath=[self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSArray *array=[[NSArray alloc] initWithContentsOfFile:filePath];
text1.text=[array objectAtIndex:0];
text2.text=[array objectAtIndex:1];
}
UIApplication *app=[UIApplication sharedApplication];//为关闭做准备
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}



程序打开时读取,程序退到后台时写入

- (void)viewDidLoad
{
[super viewDidLoad];

[self loadFromFile];
}

-(void) applicationWillResignActive:(NSNotification *)notification //在viewController中
{
[self saveToFile];
}




posted on 2012-02-09 16:29  phoenix13  阅读(530)  评论(0编辑  收藏  举报