1 //解档 2 - (id)initWithCoder:(NSCoder *)decoder 3 { 4 if (self = [super init]) { 5 unsigned int count = 0; 6 //获取类中所有成员变量名 7 Ivar *ivar = class_copyIvarList([self class], &count); 8 for (int i = 0; i<count; i++) { 9 Ivar iva = ivar[i]; 10 const char *name = ivar_getName(iva); 11 NSString *strName = [NSString stringWithUTF8String:name]; 12 //进行解档取值 13 id value = [decoder decodeObjectForKey:strName]; 14 //利用KVC对属性赋值 15 [self setValue:value forKey:strName]; 16 } 17 free(ivar); 18 } 19 return self; 20 }
1 //归档 2 - (void)encodeWithCoder:(NSCoder *)encoder 3 { 4 unsigned int count; 5 Ivar *ivar = class_copyIvarList([self class], &count); 6 for (int i=0; i<count; i++) { 7 Ivar iv = ivar[i]; 8 const char *name = ivar_getName(iv); 9 NSString *strName = [NSString stringWithUTF8String:name]; 10 //利用KVC取值 11 id value = [self valueForKey:strName]; 12 [encoder encodeObject:value forKey:strName]; 13 } 14 free(ivar); 15 }
大家在做归档与解档的时候,都需要在要归档的自定义类中服从<NSCoding>协议,并实现对应的每个方法,并在方法中对每个属性进行大部分代码的编写,但是现在只需要赋值上文中的两端代码就OK了