对象归档的定义:
成都创新互联公司专业为企业提供柴桑网站建设、柴桑做网站、柴桑网站设计、柴桑网站制作等企业网站建设、网页设计与制作、柴桑企业网站模板建站服务,10余年柴桑做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
对象归档就是将对象归档以文件的形式保存到磁盘中,使用的时候以该文件保存的路径读取文件中的内容
使用NSKeyedArichiver进行归档、NSKeyedUnarchiver进行接档,这种方式会在写入、读出数据之前对数据进行序列化、反序列化操作。
单对象归档,多个对象归档,自定义对象归档
常用的归档一般用在工具类中,对不可变的数据进行归档,可变的数据不进行归档,用起来更加方便
//1.一个对象归档
NSString *homeDictionary = NSHomeDirectory();//获取根目录
NSString *homePath = [homeDictionary stringByAppendingPathComponent:@"archiver.data"];//添加储存的文件名
//归档 toFile:路径 archiveRootObject:id对象
[NSKeyedArchiver archiveRootObject:@"对象" toFile:homePath];
//接档
id object = [NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"%@",object);
//2.将多个对象归档
NSMutableData *data = [NSMutableData data];
//归档
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
int aInt = 100;
NSString *aString = @"I is an Apple";
NSDictionary *aDict = @{@"a":@"b",@"c":@"d"};
[archiver encodeObject:@(aInt) forKey:@"aInt"];
[archiver encodeObject:aString forKey:@"aString"];
[archiver encodeObject:aDict forKey:@"aDict"];
[archiver finishEncoding];
NSString *dataHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"data.archiver"];
[data writeToFile:dataHomePath atomically:YES];
//接档
NSMutableData *muData = [[NSMutableData alloc]initWithContentsOfFile:dataHomePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:muData];
NSInteger anInt = [[unarchiver decodeObjectForKey:@"aInt"] integerValue];
NSString *anString = [unarchiver decodeObjectForKey:@"aString"];
NSDictionary *anDict = [unarchiver decodeObjectForKey:@"aDict"];
[unarchiver finishDecoding];
NSLog(@"anInt=%@,anString=%@,anDict=%@",@(anInt),anString,anDict);
//3.自定义对象归档实现copy协议
#import
@interface ArchiveCopy : NSObject
@property (copy,nonatomic) NSString *name;
@property (copy,nonatomic) NSString *anAge;
end
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:@"name"];
[aCoder encodeObject:@"anAge"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_anAge = [aDecoder decodeIntegerForKey:@"anAge"];
}
returnself;
}
#pragma mark - NSCoping
- (id)copyWithZone:(NSZone *)zone {
ArchiveCopy *copy = [[[self class] allocWithZone:zone] init];
copy.name = [self.name copyWithZone:zone];
copy.anAge = [self.address copyWithZone:zone];
return copy;
}
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款