//
// ViewController.m
// 初级数据持久化_复杂对象的存储-自定义Student类
//
// Created by YIem on 16/3/2.
// Copyright © 2016年 YIem. All rights reserved.
//
import "ViewController.h"
import "Student.h"
@interface ViewController ()
@end
@implementation ViewController(void)viewDidLoad {[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor greenColor];
NSString *fileStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Student *stu = [[Student alloc] init];
stu.name = @"YIem";
stu.sex = @"男";
stu.age = 21;
stu.score = 0.1;
NSString *stuPath = [fileStr stringByAppendingPathComponent:@"/stu.aaa"];
// 存储复杂类型数据要进行归档 读取进行反归档
// 归档时会调用NSConding协议方法, 需要在Student类中实现
// 参数1: 内容
// 参数2: 文件
[NSKeyedArchiver archiveRootObject:stu toFile:stuPath];
// 反归档
Student *backStu = [NSKeyedUnarchiver unarchiveObjectWithFile:stuPath];
NSLog(@"姓名: %@ 性别: %@ 年龄: %ld 分数: %.1f", backStu.name, backStu.sex, backStu.age, backStu.score);
}
(void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//
// Student.h
// 初级数据持久化_复杂对象的存储
//
// Created by YIem on 16/3/2.
// Copyright © 2016年 YIem. All rights reserved.
//
import
import
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) CGFloat score;
@end
//
// Student.m
// 初级数据持久化_复杂对象的存储
//
// Created by YIem on 16/3/2.
// Copyright © 2016年 YIem. All rights reserved.
//
import "Student.h"
@implementation Student(void)dealloc
{[_name release];
[_sex release];
[super dealloc];
}
(void)encodeWithCoder:(NSCoder *)aCoder
{[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.sex forKey:@"sex"];
// *注意: 不同类型数据应用不同方法
// key可以不与属性同名, 仅仅用来供反归档时对应
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeDouble:self.score forKey:@"score"];
}
// 用与上面同名(instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {self.name = [aDecoder decodeObjectForKey:@"name"];
self.sex = [aDecoder decodeObjectForKey:@"sex"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.score = [aDecoder decodeDoubleForKey:@"score"];
}
return self;
}
@end