复杂对象无法象 NSString,NSArray等简单对象一样直接通过 writeToFile 实现持久化,当对复杂对象进行持久化时需要将其转化为 NSData (归档),但获取数据时,将 NSData 转化为复杂对象 (反归档)
下面通过一个简单的 Person 类实现归档和反归档:
1.新建 Peoson 类,有两个属性 name,age,其需要遵守 <NSCoding> 协议,实现- (void)encodeWithCoder: 和 - (instancetype)initWithCoder: 方法
代码:
1//2//Person.m3//UILesson18_archiver4//5//Created by Ager on 15/11/5.6//Copyright © 2015年 Ager. All rights reserved.7//89#import"Person.h"1011@implementationPerson1213//对属性做归档处理14- (void)encodeWithCoder:(NSCoder *)aCoder{1516[aCoder encodeObject:self.name forKey:@"name"];17[aCoder encodeInteger: self.age forKey:@"age"];1819}2021//反归档处理22- (instancetype)initWithCoder:(NSCoder *)aDecoder{2324if(self =[super init]) {25self.name = [aDecoder decodeObjectForKey:@"name"];26self.age = [aDecoder decodeIntegerForKey:@"age"];27}28returnself;29}3031@end
2.完成归档,实现本地存储:(NSKeyedArchiver)
代码:
1//归档2NSMutableData *data =[NSMutableData data];3NSKeyedArchiver *keyed =[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];4[keyed encodeObject:per forKey:@"per"];5//结束归档6[keyed finishEncoding];7//归档结束,存数据8NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];910NSLog(@"%@",cachesPath);1112NSString *newPath = [cachesPath stringByAppendingPathComponent:@"person"];13[data writeToFile:newPath atomically:YES];
3.完成反归档,获取复杂对象:(NSKeyedUnarchiver)
代码:
1//反归档2NSData *data1 =[NSData dataWithContentsOfFile:newPath];3NSKeyedUnarchiver *unKeyed =[[NSKeyedUnarchiver alloc]initForReadingWithData:data1];45Person *per1 = [unKeyed decodeObjectForKey:@"per"];6[unKeyed finishDecoding];7NSLog(@"%@ %ld",per1.name,per1.age);