数据存储(归档)
1.控制器中存取方法
#import "ViewController.h"
#import "dog.h"
@interface ViewController ()
@end
@implementation ViewController
//存数据
- (IBAction)writeDataAction:(UIButton *)sender {
//1.获取存储的路径
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];
//2.创建对象
dog *superDog = [[dog alloc]init];
superDog.name = @"旺财";
superDog.age = 18;
superDog.isTrue = YES;
//3.归档 NSKeyedArchive
//如果使用归档 ,所归档的对象 必须遵守NSCoding 协议, 编码协议
[NSKeyedArchiver archiveRootObject:superDog toFile:filePath];
NSLog(@"%@",filePath);
}
//读取数据
- (IBAction)readDataAction:(UIButton *)sender {
//1.获取存储的路径
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];
//取出存储的对象
dog *superDog = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@今年%@岁了??? === %@",superDog.name,@(superDog.age),@(superDog.isTrue));
}
2.dog.h类中遵循NSCoding协议
3.dog.m类中遵循协议方法
#import "dog.h"
@implementation dog
//归档只是一个过程 告诉系统 你想存储狗的哪些属性
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeBool:self.isTrue forKey:@"isTrue"];
}
//反归档也是一个过程, 告诉系统你想让 别人获取 该对象的哪些属性
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.isTrue = [aDecoder decodeBoolForKey:@"isTrue"];
}
return self;
}
@end