创建一个新的项目,接着创建一个ViewController,如下:
具体创建的过程不多说
创建如下的.xib文件
在新建的 ViewController 的viewDidLoad方法中加入以下的代码,从文件中获得数据,填充到输入框中
- (void)viewDidLoad { [super viewDidLoad]; NSString *path = [self dataFilePath]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { NSArray *array = [[NSArray alloc]initWithContentsOfFile:path]; nameField.text = [array objectAtIndex:0]; ageField.text = [array objectAtIndex:1]; addField.text = [array objectAtIndex:2]; } UIApplication *application = [UIApplication sharedApplication]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:application]; // Do any additional setup after loading the view from its nib. }
数据以文件的形式保存,dataFilePath方法返回保存文件的路径及文件名,然后添加一个名为UIApplicationWillResignActiveNotification通知,当用户不在于应用交互时(比如程序退出),调用通知方法applicationWillResignActive,将输入框的输入内容保存到指定的文件中
-(NSString *)dataFilePath{ NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; NSLog(@"%@",path); NSString *filePath = [path stringByAppendingPathComponent:fileName]; return filePath; };
此处需要applicationWillResignActive方法
-(void)applicationWillResignActive:(NSNotification *)notification{ NSLog(@"notification"); NSMutableArray *array = [[NSMutableArray alloc]init]; [array addObject:nameField.text]; [array addObject:ageField.text]; [array addObject:addField.text]; [array writeToFile:[self dataFilePath] atomically:YES]; }
初次运行时,文件为空(不存在),输入框中内容为空,输入内容,退出,再运行,此时文件中已经有内容了,所以输入框中为保存了的数据
附上代码