用runtime来重写Coder和deCode方法 归档解档的时候使用
当我们归档自定义对象的时候,可以重写自定义Model的的encodeWithCoder和initWithCoder
开始的大概是这样的,当属性非常多的时候 这种方式就会觉得不还好 好像重复在做一样的事情 其实这块我们可以交给runtime来做
- (void)encodeWithCoder:(NSCoder *)aCoder //将属性进行编码 { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.phone forKey:@"phone"]; [aCoder encodeInteger:self.age forKey:@"age"]; } - (id)initWithCoder:(NSCoder *)aDecoder //将属性进行解码 { NSString *name1 = [aDecoder decodeObjectForKey:@"name"]; NSString *phone1 = [aDecoder decodeObjectForKey:@"phone"]; int age1 = [aDecoder decodeIntegerForKey:@"age"]; [self initWithName:name1 phone:phone1 age:age1]; return self; }
用runtime来实现上面的功能
-(void)encodeWithCoder:(NSCoder *)encoder{ unsigned int count; Ivar *ivar = class_copyIvarList([self class], &count); for (int i=0; i<count; i++) { Ivar iv = ivar[i]; const char *name = ivar_getName(iv); NSString *strName = [NSString stringWithUTF8String:name]; //利用KVC取值 id value = [self valueForKey:strName]; [encoder encodeObject:value forKey:strName]; } free(ivar); } -(id)initWithCoder:(NSCoder *)decoder{ self = [super init]; if (self) { unsigned int count = 0; //获取类中所有成员变量名 Ivar *ivar = class_copyIvarList([self class], &count); for (int i = 0; i<count; i++) { Ivar iva = ivar[i]; const char *name = ivar_getName(iva); NSString *strName = [NSString stringWithUTF8String:name]; //进行解档取值 id value = [decoder decodeObjectForKey:strName]; //利用KVC对属性赋值 [self setValue:value forKey:strName]; } free(ivar); } return self; }