????????項(xiàng)目開發(fā)中泞边,需要定義一些模型對(duì)象儲(chǔ)存用戶基本信息或數(shù)據(jù)拖陆。常規(guī)做法咪辱,我們會(huì)遵循歸檔接檔協(xié)議雄家,并對(duì)每一個(gè)屬性實(shí)現(xiàn)歸檔解檔方法:- (id)initWithCoder:(NSCoder *)decoder?和?- (void)encodeWithCoder:(NSCoder *)encoder .
? ? ? ?模型屬性隨時(shí)會(huì)增加,常規(guī)做法下碰酝,我們需要實(shí)現(xiàn)每一個(gè)屬性的歸檔和接檔,開發(fā)效率低下戴差。試想想送爸,每次增加一個(gè)屬性都要去寫歸檔解檔方法煩不煩?
? ? ? ? 利用runtime暖释,我們可以遍歷模型的所有屬性袭厂,并依次歸檔和解檔。干貨如下:
-(id)initWithCoder:(NSCoder *)aDecoder//從coder中讀取數(shù)據(jù)球匕,保存到相應(yīng)的變量中纹磺,即反序列化數(shù)據(jù)
{
? ? 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// 讀取實(shí)例變量,并把這些數(shù)據(jù)寫到coder中去亮曹。序列化數(shù)據(jù)
{
? ? 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);
}