1.归档
HMPerson *person = [HMPerson new];
person.age = 18;
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼接文件路径
NSString *filePath = [docPath stringByAppendingPathComponent:@"person.data"];
//归档
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
2.解挡
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼接文件路径
NSString *filePath = [docPath stringByAppendingPathComponent:@"person.data"];
// 解档
HMPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%d",p.age);
3.
对象必须实现<NSCoding>
#import <Foundation/Foundation.h>
@interface HMPerson : NSObject<NSCoding>
@property (nonatomic, assign) int age;
@end
4.归档对象必须实现下面两个方法
<pre name="code" class="objc">#import "HMPerson.h"
@implementation HMPerson
// 在对象归档的时候调用
// 哪些属性需要归档
// 这些属性怎么归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeInt:_age forKey:@"age"];
}
// 在对象解档的时候调用
// 哪些属性需要解档
// 这些属性怎么解档
- (id)initWithCoder:(NSCoder *)aDecoder
{
// 当父类实现了NSCoding,就能调用 [super initWithCoder]
if (self = [super init]) {
_age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
@end