zoukankan      html  css  js  c++  java
  • 通过运行时将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/ 

  • 相关阅读:
    摄像头bug查找工作总结
    高通camera结构(摄像头基础介绍)
    什么是滤波器,滤波器是干嘛用的,IIR和FIR滤波器又是什么?(回答请简洁,别浪费大家时间)
    详解摄像头各个引脚的作用关系
    Camera帧率和AE的关系
    CMOS Sensor的调试经验分享
    VSYNC与HSYNC与PCLK与什么有关系
    PCLK怎么获得?
    高清摄像头MIPI接口与ARM处理器的连接
    常用正则
  • 原文地址:https://www.cnblogs.com/NatureZhang/p/5086632.html
Copyright © 2011-2022 走看看