《精通iOS开发·第六版》数据持久化基础知识之对象归档持久化
1、BIDViewController.h文件
#import "BIDViewController.h"
#import "BIDFourLines.h"
static NSString *const kRootKey = @"kRootKey";
@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]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
BIDFourLines *fourLines = [unarchiver decodeObjectForKey:kRootKey];
[unarchiver finishDecoding];
for (int i=0; i<4; i++) {
UITextField *theField = self.lineFields[i];
theField.text = fourLines.lines[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.archive"];
}
-(void)applicationWillResignActive:(NSNotification *)notification
{
NSString *filePath = [self dataFilePath];
BIDFourLines *fourLines = [[BIDFourLines alloc] init];
fourLines.lines = [self.lineFields valueForKey:@"text"];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:fourLines forKey:kRootKey];
[archiver finishEncoding];
[data writeToFile:filePath atomically:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
2、BIDViewController.xib
3、BIDFourLines.h文件
#import <Foundation/Foundation.h>
@interface BIDFourLines : NSObject<NSCoding,NSCopying>
@property(copy,nonatomic)NSArray *lines;
@end
4、BIDFourLines.m文件
#import "BIDFourLines.h"
static NSString *const kLinesKey = @"kLinesKey";
@implementation BIDFourLines
#pragma mark -Coding
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.lines = [aDecoder decodeObjectForKey:kLinesKey];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.lines forKey:kLinesKey];
}
#pragma mark -Copying
-(id)copyWithZone:(NSZone *)zone
{
BIDFourLines *copy = [[[self class] allocWithZone:zone] init];
NSMutableArray *linesCopy = [NSMutableArray array];
for (id line in self.lines) {
[linesCopy addObject:[line copyWithZone:zone]];
}
copy.lines = linesCopy;
return copy;
}
@end
注意:如下图:
lineFields与XIB中的四个文本输入框链接