用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。
示例
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (instancetype)initWithDict:(NSDictionary *)dict;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSString *address;
@property (nonatomic, strong) NSString *company;
@property (nonatomic, strong) NSString *job;
@end
#import "Person.h"
#import <objc/runtime.h>
@implementation Person
#pragma mark - 模型转换
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self)
{
// 获取类的属性及属性对应的类型
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *attributes = [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];
// 通过property_getAttributes函数可以获得属性的名字和@encode编码
NSString *propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
// 立即释放properties指向的内存
free(properties);
// 根据类型给属性赋值
for (NSString *key in keys)
{
id value = [dict valueForKey:key];
if (value == nil)
{
continue;
}
[self setValue:value forKey:key];
}
}
return self;
}
@end
使用
// 模型转换
NSDictionary *dict = @{@"school":@"Jiaying",@"name":@"devZhang",@"age":@(35),@"company":@"ShengXue",@"job":@"iOSDev",@"address":@"龙岗坂田国际中心"};
Person *person = [[Person alloc] initWithDict:dict];
NSLog(@"name: %@", person.name);
// 打印结果
2018-07-07 00:43:42.084651+0800 DemoRuntime[2032:91805] name: devZhang