iOS文件读写
//
// MyViewController.m
// ReadWrite
//
// Created by lanou on 12-12-30.
// Copyright (c) 2012年 lanou. All rights reserved.
//
#import "MyViewController.h"
@interfaceMyViewController ()
@end
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
returnself;
}
-(void)dealloc
{
[self.userNamerelease];
[self.userPrelease];
NSNotificationCenter *center = [NSNotificationCenterdefaultCenter];
[center removeObserver:selfname:UIApplicationDidEnterBackgroundNotificationobject:nil];
[super dealloc];
}
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view.
self.userName = [[UITextFieldalloc]initWithFrame:CGRectMake(100, 40, 120, 31)];
self.userName.borderStyle = UITextBorderStyleRoundedRect;
self.userName.text = @"";
self.userName.placeholder = @"userName";
[self.viewaddSubview:self.userName];
self.userP = [[UITextFieldalloc]initWithFrame:CGRectMake(100, 80, 120, 31)];
self.userP.borderStyle = UITextBorderStyleRoundedRect;
self.userP.text = @"";
self.userP.placeholder = @"password";
[self.viewaddSubview:self.userP];
NSFileManager *fm = [NSFileManagerdefaultManager];
//如果文件存在的话
if ([fm fileExistsAtPath:[selffilePath]])
{
NSArray *arr = [NSArrayarrayWithContentsOfFile:[selffilePath]];
self.userName.text = [arr objectAtIndex:0];
self.userP.text = [arr objectAtIndex:1];
}
NSNotificationCenter *center = [NSNotificationCenterdefaultCenter];
//观察者是否进入后台程序进入后台的通知一旦程序要进入后台自动保存·
[center addObserver:selfselector:@selector(saveData) name:UIApplicationDidEnterBackgroundNotificationobject:nil];
// UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// button.frame = CGRectMake(100, 140, 120, 40);
// [button setTitle:@"save" forState:UIControlStateNormal];
// [button addTarget:self action:@selector(saveData:) forControlEvents:UIControlEventTouchUpInside];
// [self.view addSubview:button];
}
-(NSString *)filePath
{
//C的函数:搜索document文件夹 YES是绝对路径
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,/*沙盒里面找*/ YES);
NSString *documentPath = [arr objectAtIndex:0];
NSLog(@"%@",documentPath);
NSString *savePath = [documentPath stringByAppendingPathComponent/*追加一个路径的组件*/:@"secret.txt"];
NSLog(@"%@",savePath);
return savePath;
}
-(void)saveData
{
//存数组
NSArray *arr = [NSArrayarrayWithObjects:self.userName.text,self.userP.text, nil];
[arr writeToFile:[selffilePath] atomically:YES/*保证数据安全,原子性*/];
// encoding:NSUTF8StringEncoding error:nil];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

浙公网安备 33010602011771号