第四章 Runtime应用:实现字典和模型的自动转换

用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值