星空网 > 软件开发 > 操作系统

归档 NSKeyedArchiver

复杂对象无法象 NSString,NSArray等简单对象一样直接通过 writeToFile 实现持久化,当对复杂对象进行持久化时需要将其转化为 NSData (归档),但获取数据时,将 NSData 转化为复杂对象 (反归档)

下面通过一个简单的 Person 类实现归档和反归档:

1.新建 Peoson 类,有两个属性 name,age,其需要遵守 <NSCoding> 协议,实现- (void)encodeWithCoder: 和 - (instancetype)initWithCoder: 方法

  代码:

  

 1 // 2 // Person.m 3 // UILesson18_archiver 4 // 5 // Created by Ager on 15/11/5. 6 // Copyright © 2015年 Ager. All rights reserved. 7 // 8  9 #import "Person.h"10 11 @implementation Person12 13 //对属性做归档处理14 - (void)encodeWithCoder:(NSCoder *)aCoder{15   16   [aCoder encodeObject:self.name forKey:@"name"];17   [aCoder encodeInteger: self.age forKey:@"age"];18   19 }20 21 //反归档处理22 - (instancetype)initWithCoder:(NSCoder *)aDecoder{23   24   if (self = [super init]) {25     self.name = [aDecoder decodeObjectForKey:@"name"];26     self.age = [aDecoder decodeIntegerForKey:@"age"];27   }28   return self;29 }30 31 @end

 

2.完成归档,实现本地存储:(NSKeyedArchiver)

  代码:  

 1 //归档 2   NSMutableData *data = [NSMutableData data]; 3   NSKeyedArchiver *keyed = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; 4   [keyed encodeObject:per forKey:@"per"]; 5   //结束归档 6   [keyed finishEncoding]; 7   //归档结束,存数据 8   NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; 9   10   NSLog(@"%@",cachesPath);11   12   NSString *newPath = [cachesPath stringByAppendingPathComponent:@"person"];13   [data writeToFile:newPath atomically:YES];

 

3.完成反归档,获取复杂对象:(NSKeyedUnarchiver)

  代码:

1   //反归档2   NSData *data1 = [NSData dataWithContentsOfFile:newPath];3   NSKeyedUnarchiver *unKeyed = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];4   5   Person *per1 = [unKeyed decodeObjectForKey:@"per"];6   [unKeyed finishDecoding];7   NSLog(@"%@ %ld",per1.name,per1.age);

 




原标题:归档 NSKeyedArchiver

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Worten是什么平台?Worten电商平台怎么样:https://www.kjdsnews.com/a/775446.html
FBM是什么意思?亚马逊fbm自发货优缺点分析:https://www.kjdsnews.com/a/775447.html
Amazon站外推广效果不好?正确的推广方式:https://www.kjdsnews.com/a/775448.html
Lazada情人节卖什么好?情人节玩具类目也能卖“鲜花”?:https://www.kjdsnews.com/a/775449.html
高级运营都不一定会的亚马逊技术(附图文教程):https://www.kjdsnews.com/a/775450.html
谷歌SEO杂谈: 内容优化与文章字数有关吗?:https://www.kjdsnews.com/a/775451.html
在英国有分公司的中国公司:https://www.xlkjsw.com/tag/30029.html
英国成立:https://www.xlkjsw.com/tag/30031.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流