文件归档
/**
复杂对象:采用归档方式进行持久化转化
对象必须服从NSCoding协议,实现协议中方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.content forKey:@"content"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.content = [aDecoder decodeObjectForKey:@"content"];
}
return self;
}
归档(序列化) 复杂对象>>NSData>>写入
反归档(反序列化) NSData >>复杂对象
*/
/**
如果数组中存放多个复杂对象,对数组(字典)进行归档反归档操作,其中的元素对象也必须服从协议,实现协议方法.
*/
//归档
- (IBAction)archiveAction:(id)sender {
Model *model = [[Model alloc]init];
model.title = @"title";
model.content = @"荒野猎人";
//1.model >>data;
NSMutableData *data = [NSMutableData data];
//归档工具
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//归档
[archiver encodeObject:model forKey:@"m"];
//结束归档
[archiver finishEncoding];
//2. data >>writeToFile..
BOOL isSuccess = [data writeToFile:[self filePath] atomically:YES];
NSLog(@"%@",isSuccess?@"成功":@"失败");
}
- (IBAction)NarchiveAction:(id)sender {
//1.data>>model
//获取NSData数据
NSData *data = [NSData dataWithContentsOfFile:[self filePath]];
//反归档工具
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
//反归档
Model *model = [unarchiver decodeObjectForKey:@"m"];
//结束反归档.
[unarchiver finishDecoding];
NSLog(@"%@",model.content);
}
//文件路径
-(NSString *)filePath{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"data.xml"];
}