归档注意存储对象一定要遵守NSCoding协议实现其归档和解档方法,对其需要存储对象的属性进行归档和解档.
新建需要存储的对象
Person.h
//
// Person.h
// 归档和解档
//
// Created by gaocai on 16/7/18.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *name;
@end
Person.m
//
// Person.m
// 归档和解档
//
// Created by gaocai on 16/7/18.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import "Person.h"
@implementation Person
//归档存储
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:@"张三" forKey:@"name"];
[aCoder encodeInt:24 forKey:@"age"];
}
//解档读取
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self == [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
@end
ViewController.m
//
// ViewController.m
// 归档和解档
//
// Created by gaocai on 16/7/18.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
//存
- (IBAction)save:(id)sender {
//获得缓存文件路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//拼接文件存储全路径
NSString *pathFile = [cachePath stringByAppendingPathComponent:@"data.txt"];
//需要归档的对象(存储)
Person *p = [[Person alloc] init];
//开始归档 会调用Person对象实现的encodeWithCoder方法
[NSKeyedArchiver archiveRootObject:p toFile:pathFile];
}
//取
- (IBAction)read:(id)sender {
//获取缓存文件路径
NSString *cacheFile = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//拼接全路径
NSString *pathFile = [cacheFile stringByAppendingPathComponent:@"data.txt"];
//解档读取数据 会调用Person对象实现的initWithCoder方法返回一个Person对象
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:pathFile];
NSLog(@"%d", p.age);
NSLog(@"%@", p.name);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end