《精通iOS开发·第六版》数据持久化基础知识之属性列表持久化
1、BIDViewController.m文件
#import "BIDViewController.h"
@interface BIDViewController ()
@property(strong,nonatomic)IBOutletCollection(UITextField)NSArray *lineFields;
@end
@implementation BIDViewController
- (void)viewDidLoad {
[super viewDidLoad];
//视图加载完成之后(通常是从nib文件加载),做一些额外的设置
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
for (int i=0; i<4; i++) {
UITextField *theField = self.lineFields[i];
theField.text = array[i];
}
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
// Do any additional setup after loading the view from its nib.
}
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
-(void)applicationWillResignActive:(NSNotification *)notification
{
NSString *filePath = [self dataFilePath];
NSArray *array = [self.lineFields valueForKey:@"text"];
[array writeToFile:filePath atomically:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
2、BIDViewController.xib文件
注意:如下图
lineFields与XIB中的四个文本输入框链接