项目开发中,需要定义一些模型对象储存用户基本信息或数据。常规做法,我们会遵循归档接档协议,并对每一个属性实现归档解档方法:- (id)initWithCoder:(NSCoder *)decoder 和 - (void)encodeWithCoder:(NSCoder *)encoder .
模型属性随时会增加,常规做法下,我们需要实现每一个属性的归档和接档,开发效率低下。试想想,每次增加一个属性都要去写归档解档方法烦不烦?
利用runtime,我们可以遍历模型的所有属性,并依次归档和解档。干货如下:
-(id)initWithCoder:(NSCoder *)aDecoder//从coder中读取数据,保存到相应的变量中,即反序列化数据
{
self = [super init];
if (self)
{
unsigned int iVarCount = 0;
Ivar *iVarList = class_copyIvarList([self class], &iVarCount);
for (int i = 0; i < iVarCount; i++) {
Ivar var = iVarList[i];
const char *varName = ivar_getName(var);
NSString *key = [NSString stringWithUTF8String:varName];
id value = [aDecoder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(iVarList);
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder// 读取实例变量,并把这些数据写到coder中去。序列化数据
{
unsigned int iVarCount = 0;
Ivar *iVarList = class_copyIvarList([self class], &iVarCount);
for (int i = 0; i < iVarCount; i++) {
Ivar var = iVarList[i];
const char *varName = ivar_getName(var);
NSString *key = [NSString stringWithUTF8String:varName];
id value = [self valueForKey:key];
[aCoderencodeObject:value forKey:key];
}
free(iVarList);
}
网友评论