运行时_字典转模型的实现

- 拿到属性之后,用KVC的方法进行赋值,这是所有第三方字典转模型的核心算法!


#import "NSObject+KAKARunTime.h"#import@implementation NSObject (KAKARunTime)

+ (instancetype) KAKA_objWithDictionary:(NSDictionary* ) dictionary{

id object = [[self alloc] init];

//获取对象的属性

NSArray* propertyList = [self KAKA_ObjProperties];

//遍历字典进行判断

[dictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

//判断当下的Key是否是在数组当中

if ([propertyList containsObject:key]) {

//如果包含KVC赋值

[object setValue:obj forKey:key];

}

}];

return object;

}

/**

获取属性数组

@return 属性数组

*/

+ (NSArray *) KAKA_ObjProperties{

NSMutableArray * pArray = [[NSMutableArray alloc]init];

unsigned int count = 0 ;

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

NSLog(@"%zd",count);

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

objc_property_t pty = propertylist[i];

const char * cName = property_getName(pty);

NSString * pString = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];

[pArray addObject:pString];

}

free(propertylist);

return pArray.copy;

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容