归档存储

归档注意存储对象一定要遵守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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值