新建一个类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