iOS 自定义对象转NSDictionary

我们在向后台Post数据的时候,常常需要把某个对象作为参数,比如在AF的框架中,我们进行Post时,其中的para参数就是需要NSdictionary的

        Alamofire.request(.POST, url, parameters: params, encoding:.JSON, headers:headersDic)

 

要把自定义对象转成NSDictionary是一件非常麻烦的事情,这个类使用OC编写,通过Runtime访问属性列表,快速转换成字典。

Swift使用使用桥接文件即可。

 

BIDObjectToNsDictionary.h

//
//  BIDObjectToNsDictionary.h
//  WebMailSDK
//
//  Created by shenzw on 16/3/15.
//  Copyright © 2016年 51dojo. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BIDObjectToNsDictionary : NSObject
+ (NSDictionary*)getObjectData:(id)obj;
@end

 

BIDObjectToNsDictionary.m

//
//  BIDObjectToNsDictionary.m
//  WebMailSDK
//
//  Created by shenzw on 16/3/15.
//  Copyright © 2016年 51dojo. All rights reserved.
//

#import "BIDObjectToNsDictionary.h"
#import <objc/runtime.h>

@implementation BIDObjectToNsDictionary

+ (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

 

posted @ 2016-03-15 21:00  Rayshen  阅读(4062)  评论(0编辑  收藏  举报