ios数据持久化 - NSKeyedArchiver(归档)
所谓归档:将复杂对象转化为NSData类型数据(复杂-->归档-->NSData--->WriteToFile/plist方式)
注意:归档是将对象转化为数据字节,以文件的形式存储在磁盘上,
所谓反归档:将NSData类型数据转化为复杂对象(读取文件-->NSData-->反归档--->复杂对象)
归档的三种方式:
1:对自定义的对象进行归档
2:对foundation框架的对象进行归档
3:对自定义内容进行归档
注意:归档生成的文件是加密的
开始使用
1:对自定义的对象进行归档
1>.创建模型 ,并遵守NSCoding代码
@interface NSKeyedArchiverModel : NSObject<NSCoding>
2>.定义基本属性
@property(nonatomic,strong)NSString *name;
@property(nonatomic,strong)NSString *gender;
@property(nonatomic,assign)int age;
3>.实现代理方法
//归档(序列化)
//对NSKeyedArchiverModel对象进行归档时,此方法执行
//对NSKeyedArchiverModel中想要进行归档的所有属性,进行序列化操作
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.gender forKey:@"gender"];
[aCoder encodeInt:self.age forKey:@"age"];
}
//反归档(反序列化)
//对NSKeyedArchiverModel对象进行反归档时,该方法执行
//创建一个新的NSKeyedArchiverModel对象,所有属性都是通过反序列化得到
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.gender = [aDecoder decodeObjectForKey:@"gender"];
self.age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
4>.设置数据并进行归档操作
NSKeyedArchiverModel *per = [NSKeyedArchiverModel new];
per.name = @"小美眉";
per.gender = @"女";
per.age = 18;
//准备路径:
NSString *path = NSHomeDirectory();
NSLog(@"%@",path);
path = [path stringByAppendingPathComponent:@"singeGirl.txt"];
//1:准备存储数据的对象
NSMutableData *data = [NSMutableData data];
//2:创建归档对象
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//3:开始归档
[archiver encodeObject:per forKey:@"person"];
//4:完成归档
[archiver finishEncoding];
//5:写入文件当中
BOOL result = [data writeToFile:path atomically:YES];
if (result) {
NSLog(@"归档成功:%@",path);
}else
{
NSLog(@"归档不成功!!!");
}
5>.--- 反归档/反序列化/解码/解档 ----
//准备解档路径
NSData *myData = [NSData dataWithContentsOfFile:path];
//创建反归档对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
//反归档
per = [unarchiver decodeObjectForKey:@"person"];
//完成反归档
[unarchiver finishDecoding];
//测试
NSLog(@"解码输出=%@=%@=%d",per.name,per.gender,per.age);
2:对foundation框架的对象进行归档
//归档
//1:创建路径
NSString *Doucuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
NSString *path = [Doucuments stringByAppendingString:@"file.plist"];
//2:归档(不需要结束方法)
NSDictionary *dict = @{
@"name" : @"HJM",
@"age" : @18,
@"sex" : @"男",
@"arr" : @[@1,@2,@3],
};
BOOL result = [NSKeyedArchiver archiveRootObject:dict toFile:path];
if (result) {
NSLog(@"框架中的归档%@",path);
}
//反归档
NSDictionary *newArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"框架的结档%@ =%@",newArray,newArray[@"name"]);