码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 自定义类型转换为Dictionary

时间:2015-01-23 13:04:45      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

IOS 自定义model如果要转换位json与服务器进行交互的时候,我把model数据类型先转换为了dictionary然后在进行json序列化。

 

#import <objc/runtime.h>


@implementation ConvertToCustomClass
+ (NSMutableArray *)convertCustomClassToDictionary:(NSMutableArray *)array{
    NSMutableArray *customArray = [NSMutableArray array];
    for (id customClass in array) {
        NSString *className = NSStringFromClass([customClass class]);//获取类名
        const char *cClassName = [className UTF8String];//类名编码方式
        id theClass = objc_getClass(cClassName);//获取当前类类型
        unsigned int outCount, i;
     
        //获取该类的所有属性
        objc_property_t *properties = class_copyPropertyList(theClass, &outCount);
        NSMutableArray *propertyNames = [[NSMutableArray alloc] initWithCapacity:1];
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
             //property_getName()返回属性的名字
            NSString *propertyNameString = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            [propertyNames addObject:propertyNameString];
            //property_getAttributes()返回属性的属性
            NSLog(@"%s %s\n", property_getName(property), property_getAttributes(property));
        }
        NSMutableDictionary *finalDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        for(NSString *key in propertyNames)
        {
            SEL mySel = NSSelectorFromString(key);
            id value = [customClass performSelector:mySel];
            if (value == nil)
            {
                value = [NSNull null];
            }
            [finalDict setObject:value forKey:key];
            NSLog(@"%@     %@\n", value, key);
        }
        [customArray addObject:finalDict];
    }
    return customArray;
}
@end
 

IOS 自定义类型转换为Dictionary

标签:

原文地址:http://www.cnblogs.com/evangao/p/4243772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!