用runtime 进行归档

#import "BaseModel.h"

#import

@implementation BaseModel

// 归档

- (void)encodeWithCoder:(NSCoder *)enCoder{

//归档存储自定义对象

unsigned int count = 0;

//获得指向该类所有属性的指针

objc_property_t *properties = class_copyPropertyList([self class], &count);

for (int i =0; i < count; i ++) {

//获得

objc_property_t property = properties[i];

//根据objc_property_t获得其属性的名称--->C语言的字符串

const char *name = property_getName(property);

NSString *key = [NSString stringWithUTF8String:name];

// 编码每个属性,利用kVC取出每个属性对应的数值

[enCoder encodeObject:[self valueForKeyPath:key] forKey:key];

}

free(properties);

}

// 解档

- (id)initWithCoder:(NSCoder *)aDecoder{

//归档存储自定义对象

unsigned int count = 0;

//获得指向该类所有属性的指针

objc_property_t *properties = class_copyPropertyList([self class], &count);

for (int i =0; i < count; i ++) {

objc_property_t property = properties[i];

//根据objc_property_t获得其属性的名称--->C语言的字符串

const char *name = property_getName(property);

NSString *key = [NSString stringWithUTF8String:name];

//解码每个属性,利用kVC取出每个属性对应的数值

[self setValue:[aDecoder decodeObjectForKey:key] forKeyPath:key];

}

free(properties);

return self;

}

@end


然后其他类使用,只要继承它就好了

#import "BaseModel.h"

@interface PeopleModel : BaseModel

@property (nonatomic, copy) NSString *name;

@property (nonatomic, assign) NSInteger age;

@end

OR

你可能感兴趣的:(用runtime 进行归档)