归档:
1、使用NSMutableData 实例作为归档的存储数据
2、添加归档内容
3、完成归档
4、把归档的数据存入到硬盘
解档:
读取归档的内容,还原对象类型的操作
1、从硬盘中读取文件,生成NSData实例
2、根据Data实例进行创建和初始化还原归档文件
3、还原文件,根据key去访问相应的值
//1、归档I NSKeyedArchiver
NSArray *array=@[ @1 ,@2,@3 ,@4];
if ([NSKeyedArchiver archiveRootObject:array toFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/test.plist"]]) {
NSLog(@"array归档成功");
}
else{
NSLog(@"归档失败");
}
//解档
NSArray *arrayUnar=[NSKeyedUnarchiver unarchiveObjectWithFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/test.plist"]];
NSLog(@"array:%@",arrayUnar);
//定义一个字典,将其归档,在一个类中定义一个方法解档
NSDictionary *dict=@{@"name":@"姓名",@"sex":@"性别",@"age":@"年龄"};
if ([NSKeyedArchiver archiveRootObject:dict toFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testI.plist"]]) {
NSLog(@"dict归档成功");
}
else{
NSLog(@"归档失败");
}
Person *per=[[Person alloc]init];
[per unarchive];
//2、归档II
//定义一个空的可变数组流
NSMutableData *mutdata=[[NSMutableData alloc]init];
//实例一个归档的对象
NSKeyedArchiver *arch=[[NSKeyedArchiver alloc]initForWritingWithMutableData:mutdata];
//开始编码
[arch encodeObject:dict forKey:@"dictEncode"];
//结束编码
[arch finishEncoding];
//将编码后的数据写入文件并保存
[mutdata writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testII.plist"]
atomically:YES];
//定义一个NSData对象从归档文件中获取到的数据流
NSData *data=[[NSData alloc]initWithContentsOfFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testII.plist"]];
//解档
NSKeyedUnarchiver *Unarch=[[NSKeyedUnarchiver alloc]initForReadingWithData:data];
NSDictionary *dictI=[Unarch decodeObjectForKey:@"dictEncode"];
NSLog(@"dictI:%@",dictI);