runtime 获取类的属性,方法,成员变量,以及协议 字典转model 总结

runtime 的使用笔记

1 runtime 获取类的属性,方法,成员变量,以及协议

unsigned int count;
    //获取属性列表
    objc_property_t *propertyList=class_copyPropertyList([model class], &count);
    for (unsigned int i=0; i<count; i++) {
        const char *propertyName=property_getName(propertyList[i]);
        NSLog(@"propertyName----->%@",[NSString stringWithUTF8String:propertyName]);
        NSLog(@"propertyValue----->%@",[model valueForKey:[NSString stringWithUTF8String:propertyName]]);
        NSLog(@"propertyValueClass----->%@",[[model valueForKey:[NSString stringWithUTF8String:propertyName]] class]);
    }
    //获取方法列表
    Method *methodList=class_copyMethodList([model class], &count);
    for (unsigned int i=0; i<count; i++) {
        Method method=(methodList[i]);
        NSLog(@"method----->%@",NSStringFromSelector(method_getName(method)));
    }
    //获取成员变量列表
    Ivar *ivarList=class_copyIvarList([model class], &count);
    for (unsigned int i=0; i<count; i++) {
        Ivar myIvar=ivarList[i];
        const char *ivarName=ivar_getName(myIvar);
        NSLog(@"Ivar----->%@",[NSString stringWithUTF8String:ivarName]);
    }
    
    //获取协议列表
    __unsafe_unretained Protocol **protocolList=class_copyProtocolList([model class], &count);
    for (unsigned int i=0; i<count; i++) {
        Protocol *myProtocal=protocolList[i];
        const char *protocolName=protocol_getName(myProtocal);
        NSLog(@"protocol----->%@",[NSString stringWithUTF8String:protocolName]);
    }


2 runtime 简单字典转model  自定义方法

model.h

@property (nonatomic ,copy)NSString *propertyA;
@property (nonatomic ,copy)NSString *propertyB;
@property (nonatomic ,copy)NSString *propertyC;

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary;

model.m

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary{
    return [[self alloc]initWithDictionary:dictionary];
}

- (instancetype)initWithDictionary:(NSDictionary *)dictionary{
    self = [super init];
    if (self) {
        unsigned int count;
        //获取属性列表 遍历并赋值
        objc_property_t *propertyList=class_copyPropertyList([self class], &count);
        for (unsigned int i=0; i<count; i++) {
            const char *propertyName=property_getName(propertyList[i]);
            //属性名
            NSString *propertyNameStr = [NSString stringWithUTF8String:propertyName];
            NSString *propertyValue = [dictionary objectForKey:propertyNameStr];
            if ([WYHTools isBlankString:propertyValue]) {
                propertyValue = @"暂无";
            }
            [self setValue:propertyValue forKey:propertyNameStr];
        }
    }
    return  self;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值