zoukankan      html  css  js  c++  java
  • ObjC 巧用反射和KVC实现JSON快速反序列化成对象

    1.简单的KVC介绍

    KVC是一种间接访问对象属性的机制,不直接调用getter 和 setter方法,而使用valueForKey 来替代getter 方法,setValue:forKey来代替setter方法。

    之前的一篇博客(http://www.cnblogs.com/rayshen/p/5006619.html),在探讨如何把某个对象进行序列化的时候,其实已经使用到KVC,如果某个类遵循NSCoding协议就能编码成NSData*(字节流)。

    具体KVC使用的示例为:

    Persion *persion =  [ [Persion alloc] init ];
    //不使用KVC
    persion.name = @"shen" ;
    //使用KVC的写法
    [persion  setValue:@"shen" forKey:@"name"];

    上面是利用KVC访问类里的某个属性,下面利用KVC直接访问类里的类里的某个属性

    复制代码
    //不使用KVC
    Persion *persion =  [ [Persion alloc] init ];
    Phone *phone = persion.phone;
    Battery *battery = phone.battery;
    //使用KVC
    Battery *battery = [persion valueForKeyPath: @"phone.battery" ];

    2.自定义Class实现快速反序列化

    -(id)initWithDictionary:(NSDictionary *)dic{
        if(dic){
            if(self=[super init]){
                unsigned int outCount=0;
                //获得该class所有property的key的数组,和property总数
                objc_property_t * const properties=class_copyPropertyList([self class], &outCount);
                if(outCount>0){
                    for(int i=0;i<outCount;i++){
                        //属性名转换成NSString
                        NSString *propertyName = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding];
                        //根据属性名,从字典从取出内容
                        id value=[dic objectForKey:propertyName];
                        if(value){
                        //利用setValue快速赋值
                            [self setValue:value forKey:propertyName];
                        }
                    }
                }
                return self;
            }
        }
        return nil;
    }
    

    上面的代码进行JSON反序列化成对象的方式的缺点是:

    1.无法进行嵌套对象的反序列化(进行递归封装后就可以实现了)。

    2.必须保持JSON的Key和Property名是一致的。

    3.对象内容不易修改,默认为NSArray和NSDictionary,都是不可变的数组和字典。后期操作比较麻烦。

  • 相关阅读:
    拉丁舞身形研究之恰恰恰
    和我们一起建设中文最专业的GPU站点——OpenGPU.org
    Signal Shading Theory?
    GPGPU实时光线刻蚀模拟
    Geometry Shader Concepts & Examples
    基于GPU屏幕空间的精确光学折射效果
    宽容
    我的相册
    Ninject 笔记之 对象范围 Kevin
    Attempt to write to a readonly database Sqlite Kevin
  • 原文地址:https://www.cnblogs.com/rayshen/p/5082690.html
Copyright © 2011-2022 走看看