实现字典和模型的自动转换(MJExtension)
作者:
骑着毛驴走起来 | 来源:发表于
2020-03-05 21:58 被阅读0次- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [super init]) {
//(1)获取类的属性及属性对应的类型
NSMutableArray * keys = [NSMutableArray array];
unsigned int outCount;
objc_property_t * properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通过property_getName函数获得属性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
}
//立即释放properties指向的内存
free(properties);
//(2)根据类型给属性赋值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
本文标题:实现字典和模型的自动转换(MJExtension)
本文链接:https://www.haomeiwen.com/subject/vmqklhtx.html
网友评论