对象归档的定义:
对象归档就是将对象归档以文件的形式保存到磁盘中,使用的时候以该文件保存的路径读取文件中的内容
使用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 <Foundation/Foundation.h>
@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"];
}
return self;
}
#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;
}