ios 通过runtime 获取属性列表并修改变量值

JSONModel第三方框架, 向服务器发起一个请求, 返回后的数据直接就是一个可用的Model。

其中核心技术使用的便是runtime的反射机制,通过runtime将解析好的json数据直接存放到了我们的对象模型中。

以下为自己写的一个测试demo,实现了获取属性列表并进行改值

/** 获取属性列表 */
-(void)getProperties{
    u_int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    
    for (int i = 0; i < count; i++) {
        const char *propertyName = property_getName(properties[i]);
        const char *attributes = property_getAttributes(properties[i]);
        NSString *str = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
        NSString *attributesStr = [NSString stringWithCString:attributes encoding:NSUTF8StringEncoding];
        NSLog(@"propertyName : %@", str);
        NSLog(@"attributesStr : %@", attributesStr);
    }
}
/** 修改变量 */
- (id)updateVariable
{
    //获取当前类
    id theClass = [self class];
    //初始化
    id otherClass = [[theClass alloc] init];
    
    unsigned int count = 0;
    //获取属性列表
    Ivar *members = class_copyIvarList([otherClass class], &count);
    
    //遍历属性列表
    for (int i = 0 ; i < count; i++) {
        Ivar var = members[i];
        //获取变量名称
        const char *memberName = ivar_getName(var);
        //获取变量类型
        const char *memberType = ivar_getTypeEncoding(var);
        
        NSLog(@"%s----%s", memberName, memberType);
        
        Ivar ivar = class_getInstanceVariable([otherClass class], memberName);
        
        NSString *typeStr = [NSString stringWithCString:memberType encoding:NSUTF8StringEncoding];
        //判断类型
        if ([typeStr isEqualToString:@"@\"NSString\""]) {
            //修改值
            object_setIvar(otherClass, ivar, @"abc");
        }else{
            object_setIvar(otherClass, ivar, [NSNumber numberWithInt:99]);
        }
    }
    return otherClass;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值