// Person.h
// 归档和反归档
//
// Created by lanou3g on 16/2/24.
// Copyright © 2016年 GlongF. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property(nonatomic,strong) NSString *name;
@property(nonatomic,assign) NSInteger age;
// Person.m
// 归档和反归档
//
// Created by lanou3g on 16/2/24.
// Copyright © 2016年 GlongF. All rights reserved.
//
#import "Person.h"
@implementation Person
// 实现协议中的方法
// 编码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
// 反编码
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
// ViewController.m
// 归档和反归档
//
// Created by lanou3g on 16/2/24.
// Copyright © 2016年 GlongF. All rights reserved.
//
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
NSLog(@"doc = %@",documentPath);
#pragma mark ------------------------ 复杂对象持久化 -----------------
// 过程:复杂对象 -> 归档 -> NSData -> 写入文件
Person *person = [[Person alloc] init];
person.age = 22;
person.name = @"张三";
NSMutableData *data = [NSMutableData data];
// 创建归档器
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 归档
// 将归档结束的data写入文件
NSString *filePath = [documentPath stringByAppendingPathComponent:@"personFile.txt"];
[data writeToFile:filePath atomically:YES];
NSLog(@"filePath = %@",filePath);
NSLog(@"data = %@",data);
#pragma mark -- 从文件中读取复杂对象
//过程 (读取文件 -> NSData -> 反归档 -> 复杂对象)
// 读取数据
NSData *dataRead = [NSData dataWithContentsOfFile:filePath];
// 创建反归档工具
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:dataRead];
Person *person1 = [unArchiver decodeObjectForKey:@"person1"];
[unArchiver finishDecoding];
NSLog(@"person name = %@",person1.name);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
179



被折叠的 条评论
为什么被折叠?



