归档NSKeyedArchiver

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

复杂对象无法象 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);

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航