首先demo结构
33260F48-9263-45DC-8901-A1B0D0C856BB.png
1, model, .m文件中不需要写任何东西
B838F142-F2D6-407A-BF4F-44E61DD7FF6C.png
2,创建一个NSObject的扩展
4A9EA170-9907-47AC-A18A-CBFCF23D9154.png
.m文件内容
#import "NSObject+FYJsonToModel.h"
#import <objc/runtime.h>
@implementation NSObject (FYJsonToModel)
// 利用 Runtime
-(void)fy_modelSetWithDictionary:(NSDictionary *)dictionary
{
if (dictionary == nil){
return;
}
unsigned int outCount =0;
Ivar*vars =class_copyIvarList([self class], &outCount);//获取到所有的成员变量列表
//遍历所有的成员变量
for(int i =0; i < outCount; i++) {
Ivar ivar = vars[i];//取出第i个位置的成员变量
const char*propertyName =ivar_getName(ivar);//获取变量名
NSString*proOcName = [NSString stringWithUTF8String:propertyName];
id jsonValue = [dictionary objectForKey:[proOcName stringByReplacingOccurrencesOfString:@"_" withString:@""]];
object_setIvar(self, ivar,jsonValue);
}
}
@end
3,使用
A4DF7772-A0B0-416A-9AF5-D2226DDA5DCF.png
我们不生产代码 我们只是代码的搬运工 原文连接