标签:
复杂对象无法象 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 Person
12
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);
标签:
原文地址:http://www.cnblogs.com/Ager/p/4940984.html