数据的归档和反归档(序列化和反序列化)

Posted on 2016-06-30 21:23  柠檬片  阅读(100)  评论(0)    收藏  举报
 1 //1.首先,类要继承<NSCoding>协议
 2 #import <Foundation/Foundation.h>
 3 
 4 @interface CZPerson : NSObject<NSCoding>
 5 @property (nonatomic, copy) NSString *name;
 6 @property (nonatomic, copy) NSString *phone;
 7 @end
 8 
 9 //2.类中要实现NSCoding协议中的两个方法
10 #import "CZPerson.h"
11 
12 @implementation CZPerson
13 //归档  告诉系统要存储对象的哪些属性
14 - (void)encodeWithCoder:(NSCoder *)aCoder
15 {
16     [aCoder encodeObject:self.name forKey:@"name"];
17     [aCoder encodeObject:self.phone forKey:@"phone"];
18 }
19 
20 //反归档  读取对象的哪些属性
21 - (instancetype)initWithCoder:(NSCoder *)aDecoder
22 {
23     if (self = [super init])
24     {
25         self.name = [aDecoder decodeObjectForKey:@"name"];
26         self.phone = [aDecoder decodeObjectForKey:@"phone"];
27     }
28     return self;
29 }
30 @end
归档和反归档
 1 #import "ViewController.h"
 2 #import "CZPerson.h"
 3 
 4 @interface ViewController ()
 5 
 6 @end
 7 
 8 @implementation ViewController
 9 
10 - (void)viewDidLoad {
11     [super viewDidLoad];
12     // Do any additional setup after loading the view, typically from a nib.
13     
14    //反归档
15     //1.获取documents路径
16     NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
17     //2.拼接文件名
18     NSString * fileName = [path stringByAppendingPathComponent:@"contact.app"];
19     
20     //3.反归档读取数据
21    CZPerson * person = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
22     
23     NSLog(@"name === %@  phone == %@",person.name,person.phone);
24 }
25 - (void) test01
26 {
27     //创建联系人对象
28     CZPerson * person = [[CZPerson alloc] init];
29     
30     //给Person属性赋值
31     person.name = @"JackMeng";
32     person.phone = @"10086";
33     
34     //1.获取documents路径
35     NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
36     
37     //2,拼接文件名
38     NSString * fileName = [path stringByAppendingPathComponent:@"contact"];
39     
40     //通过归档的方式存储
41     [NSKeyedArchiver archiveRootObject:person toFile:fileName];
42     
43     NSLog(@"%@",fileName);
44 }
45 - (void)didReceiveMemoryWarning {
46     [super didReceiveMemoryWarning];
47     // Dispose of any resources that can be recreated.
48 }
49 
50 @end
使用归档和反归档