9.23 归档&解归档

新建一个类Animal

Animal.h文件

@property(nonatomic,copy)NSString *name;
新建了一个name变量

Animal.m文件中写方法

#import "Animal.h"

@interface Animal ()<NSCoding>

@end

@implementation Animal

//这里写两个Animal必须实现的两个方法,归档和解归档

//解归档    读取磁盘内我们需要的信息

- (instancetype)initWithCoder:(NSCoder *)aDecoder{   

    self = [super init];

    if (self) {    

        self.name = [aDecoder decodeObjectForKey:@"kname"];

    }

    return self;

}

//归档      把我们要写的东西写入磁盘

- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.name forKey:@"kname"];

}

@end

@"kname"可以是任意的字符串,作为编码的key,归档和解归档都可以根据key找到对应的文件

ViewController.m 文件中实现方法

#import "ViewController.h"

#import "Animal.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //创建一个path路径

    NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/animal.cache"];

    

    //实现归档

    if(![NSKeyedUnarchiver unarchiveObjectWithFile:path]){   

        //判断它读没读到文件,如果没有读到,我们就创建下面的归档方法

        Animal *animal = [Animal new];

        animal.name = @"hello_animal";

        [NSKeyedArchiver archiveRootObject:animal toFile:path];   

    }

    NSLog(@"path = %@",path);

    //解归档

    NSString *animal2 = (NSString *)[NSKeyedUnarchiver unarchiveObjectWithFile:path];

    //    NSLog(@"animal2.name = %@",animal2.name);   

    NSLog(@"animal2 = %@",animal2);

}

@end

归档:存到磁盘上 initWithCoder
解归档:从磁盘上读出来,转为OC的语言 encodeWithCoder

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 27、ViewController的didReceiveMemoryWarning是在什么时候调用的?默认的操作是...
    烟雨平生花飞舞阅读 628评论 0 1
  • 一、归档的基本概念 之前将数据保存本地,只能是字符串、数组、字典、NSNuber、BOOL等容器类对象对象,不能将...
    空白Null阅读 5,241评论 1 10
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,814评论 0 9
  • 下面是我最近两年学习OC中的一些基础知识,对于学习OC基础知识的人可能有些帮助,拿出来分享一下,还是那句话不喜勿喷...
    小小赵纸农阅读 2,662评论 1 7
  • 转载自:http://www.mamicode.com/info-detail-957988.html 1、iOS...
    哆啦_阅读 2,339评论 0 2