重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
对象归档的定义:
目前创新互联已为上1000+的企业提供了网站建设、域名、网站空间、网站托管维护、企业网站设计、大田网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。对象归档就是将对象归档以文件的形式保存到磁盘中,使用的时候以该文件保存的路径读取文件中的内容
使用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"];
}
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;
}
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。