1.遵守协议
@interface xxx : NSObject<NSCoding>
2归档方法
BOOL isSucess = [NSKeyedArchiver archiveRootObject:要归档的对象 self toFile:@"要归档的路径"];
if (isSucess) {
NSLog(@"用户信息保存成功");
} else {
NSLog(@"用户信息保存失败");
}
3解归档方法
self = [NSKeyedUnarchiver unarchiveObjectWithFile:@"归档是保存的路径"];
4 归档和解归档的具体实现 ->协议方法
//归档时走的协议方法 在这个方法中将想要保存的对象归档
- (void)encodeWithCoder:(NSCoder *)coder;
[aCoder encodeObject:@"值" forKey:@"key"];
//解归档时走的协议方法 取出归档的对象
- (nullable instancetype)initWithCoder:(NSCoder *)coder; // NS_DESIGNATED_INITIALIZER
id value = [aDecoder decodeObjectForKey:@"key"];
value = @"值"
5利用runtime将整个类的属性归档
/*
使用runtime进行解档与归档。 利用runtime把类的属性全部取出 进行操作
*/
-(void)encodeWithCoder:(NSCoder *)aCoder{
unsigned int count = 0;
Ivar *ivarLists = class_copyIvarList([归档的类 NSObject class], &count);// 注意下面分析
for (int i = 0; i < count; i++) {
const char* name = ivar_getName(ivarLists[i]);
NSString* strName = [NSString stringWithUTF8String:name];
//以对象name为key进行存储 方便取出
[aCoder encodeObject:[self valueForKey:strName] forKey:strName];
}
free(ivarLists);
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivarLists = class_copyIvarList([归档的类 NSObject class], &count);
for (int i = 0; i < count; i++) {
const char* name = ivar_getName(ivarLists[i]);
NSString* strName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
id value = [aDecoder decodeObjectForKey:strName];
[self setValue:value forKey:strName];//因为存储的时候是通过对象的name进行存储 所以通过kvc直接赋值
}
free(ivarLists);
}
return self;
}