Runtime 自动化归档
Runtime的使用
1 (id)initWithCoder:(NSCoder *)decoder 2 { 3 if (self = [super init]) { 4 unsigned int count = 0; 5 Ivar *ivars = class_copyIvarList([self class], &count); 6 7 for (int i = 0; i<count; i++) { 8 9 Ivar ivar = ivars[i]; 10 11 // 获取成员变量 12 const char *name = ivar_getName(ivar); 13 14 // 归档 15 NSString *key = [NSString stringWithUTF8String:name]; 16 id value = [decoder decodeObjectForKey:key]; 17 18 // 设置 19 [self setValue:value forKey:key]; 20 } 21 22 free(ivars); 23 } 24 return self; 25 }
1 - (void)encodeWithCoder:(NSCoder *)encoder 2 { 3 4 unsigned int count = 0; 5 Ivar *ivars = class_copyIvarList([self class], &count); 6 7 for (int i = 0; i<count; i++) { 8 9 Ivar ivar = ivars[i]; 10 11 //获取成员变量 12 const char *name = ivar_getName(ivar); 13 14 // 归档 15 NSString *key = [NSString stringWithUTF8String:name]; 16 id value = [self valueForKey:key]; 17 [encoder encodeObject:value forKey:key]; 18 } 19 20 free(ivars); 21 }