• 对象转字典 iOS


    最近在开发SDK,我开放给客户model类设置信息后,对象转字典,POST给后台。

    思路:通过Runtime访问属性列表,快速转换成字典。

    FRObjectToDictionary.h类

    #import <Foundation/Foundation.h>

     

    @interface FRObjectToDictionary : NSObject

    + (NSDictionary*)getObjectData:(id)obj;

    @end

     

     

    FRObjectToDictionary.m类

     

     

    #import "FRObjectToDictionary.h"

    #import <objc/runtime.h>

    @implementation FRObjectToDictionary

     

    + (NSDictionary*)getObjectData:(id)obj

    {

        NSMutableDictionary *dic = [NSMutableDictionary dictionary];

        unsigned int propsCount;

        objc_property_t *props = class_copyPropertyList([obj class], &propsCount);//获得属性列表

        for(int i = 0;i < propsCount; i++)

        {

            objc_property_t prop = props[i];

            

            NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];//获得属性的名称

            id value = [obj valueForKey:propName];//kvc读值

            if(value == nil)

            {

                value = [NSNull null];

            }

            else

            {

                value = [self getObjectInternal:value];//自定义处理数组,字典,其他类

            }

            [dic setObject:value forKey:propName];

        }

        return dic;

    }

     

     

    + (id)getObjectInternal:(id)obj

    {

        if([obj isKindOfClass:[NSString class]]

           || [obj isKindOfClass:[NSNumber class]]

           || [obj isKindOfClass:[NSNull class]])

        {

            return obj;

        }

        

        if([obj isKindOfClass:[NSArray class]])

        {

            NSArray *objarr = obj;

            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];

            for(int i = 0;i < objarr.count; i++)

            {

                [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];

            }

            return arr;

        }

        

        if([obj isKindOfClass:[NSDictionary class]])

        {

            NSDictionary *objdic = obj;

            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];

            for(NSString *key in objdic.allKeys)

            {

                [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];

            }

            return dic;

        }

        return [self getObjectData:obj];

    }

     

     

    @end

     

     

    调用时:

    [FRObjectToDictionary getObjectData:aModel]

  • 相关阅读:
    FirstBlood溢出攻击
    ShellCode
    OD分析-熊猫烧香
    IDA分析-熊猫烧香
    PentestBOX教程
    安全从业人员常用工具指引-freebuf
    安全从业人员常用工具指引
    Python 网络编程
    10个免费的游戏开发引擎
    用树莓派搭建你自己的Web服务器,以及一个可以外网访问的Blog
  • 原文地址:https://www.cnblogs.com/huangzs/p/7743731.html
Copyright © 2020-2023  润新知