iOS解档与归档
Posted fantasy3588
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS解档与归档相关的知识,希望对你有一定的参考价值。
// 解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
unsigned int count;
Ivar* ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char* name = ivar_getName(ivar);
NSString* strName = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:strName];
[self setValue:value forKey:strName];
}
free(ivars);
}
return self;
}
// 归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
unsigned int count;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char* name = ivar_getName(ivar);
NSString* strName = [NSString stringWithUTF8String:name];
id value = [self valueForKey:strName];
[aCoder encodeObject:value forKey:strName];
}
free(ivars);
}
头文件必须导入
#import <objc/runtime.h>
以上是关于iOS解档与归档的主要内容,如果未能解决你的问题,请参考以下文章
iOS 数据的归档(NSKeyedArchiver )与数据的解档(NSKeyedUnarchiver) 加密 提高安全性