其中TRPerson为自定义的继承自NSObject的类的子类 其中有两个属性,name 和 age
.h文件
#import
@interface TRPerson : NSObject<</span>NSCoding>
@property (nonatomic,strong)NSString *name;
@property (nonatomic,strong)NSNumber * age;
//初始化方法
- (id)initWithName:(NSString*)name withAge:(NSNumber *)age;
@end
.m文件
#import "TRPerson.h"
@implementation TRPerson
- (id)initWithName:(NSString *)name withAge:(NSNumber *)age{
if (self=[super init]) {
self.age=age;
self.name=name;
}
return self;
}
#pragma mark - NSCoding
//对属性进行解码(时机:执行encodeObject方法)
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self= [super init];
if (self) {
self.name= [aDecoder decodeObjectForKey:@"name"];
self.age=[aDecoder decodeObjectForKey:@"age"];
}
return self;
}
//对属性进行编码的方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.age forKey:@"age"];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (NSString *)description{
TRPerson *person=[[TRPerson alloc]initWithName:self.name withAge:self.age];
return [NSString stringWithFormat:@"name:%@ age:%@",person.name ,person.age];
}
@end
ViewController中的viewDidLoad方法中实现数据的归档和解挡
- (void)viewDidLoad {
[super viewDidLoad];
//准备工作
//将自定义的TRPerson对象进行归档(写)
TRPerson *person=[[TRPerson alloc]initWithName:@"张飞" withAge:@20];
//Documents/archiving
NSString *doumentsPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES).firstObject;
NSString *archiverPath = [doumentsPath stringByAppendingPathComponent:@"archving"];
//1.可变数据类型
NSMutableData *data=[NSMutableData data];
//2.归档对象
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//3.编码
[archiver encodeObject:person forKey:@"person"];
//4.编码完成
[archiver finishEncoding];
//5.写入文件
[data writeToFile:archiverPath atomically:YES];
//将自定义的TRPerson对象进行解挡(读)
//1.读取数据
NSData *readingData=[NSData dataWithContentsOfFile:archiverPath];
//2.解码对象
NSKeyedUnarchiver *unArchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:readingData];
//3.解码
TRPerson *personRead=[unArchiver decodeObjectForKey:@"person"];
//4.完成解码
[unArchiver finishDecoding];
//验证
NSLog(@"%@",personRead );
}