通过运行时将Model转成字典输出

或许我们会有一些这样的场景,定义一个Model类来临时存储一些数据,然后稍后再把这些数据组织成 Dictionary,再做其他用途。

可以通过运行时机制 获取类的PropertyList,然后根据 其中的某个Property找到对应的iVar,通过ivar 获取到对应的值。通过属性名作为字典键值,iVar值作为value付给Dic,至此结束。

- (NSDictionary *)dicSerializeObject
{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSString *className = NSStringFromClass([self class]);
    id class = objc_getClass([className UTF8String]);
    
    // 获取类中的property
    unsigned int propertyCount;
    objc_property_t *properties = class_copyPropertyList(class, &propertyCount);
    
    for (unsigned int i = 0; i < propertyCount; i++)
    {
        objc_property_t property = properties[i];
        const char *cPropertyName = property_getName(property);
        
        // 得到属性名
        NSString *propertyName = [NSString stringWithCString:cPropertyName encoding:NSUTF8StringEncoding];
        
        // 获取实例变量
        Ivar ivar = class_getInstanceVariable([self class], cPropertyName);
        if (ivar == nil)
        {
            ivar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@", propertyName] UTF8String]);
        }
        
        // 赋值
        if(ivar != nil)
        {
            id propertyValue = object_getIvar(self, ivar);
            
            if (propertyValue)
            {
                [dictionary setObject:propertyValue forKey:propertyName];
            }
        }
    }
    
    free(properties);
    
    return dictionary;
}

 将这个方法定义实现在NSObject的Category中,即可方便使用。

 

还看到这一篇博客(JSON转Model思路):http://ios.jobbole.com/82975/ 

 

转载于:https://www.cnblogs.com/NatureZhang/p/5086632.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值