IOS NSDictionary扩展映射model(字典--》model;字典==》string)

#import <Foundation/Foundation.h>

@interface NSDictionary (MS)
+(NSString*)dictionary2string:(NSDictionary*)dic;
/**
 *  字典转换成Model
 *
 *  @param model 要转换的对象
 */
- (void)toModel:(id)model;

@end
#import "NSDictionary+MS.h"

@implementation NSDictionary (MS)
+(NSString*)dictionary2string:(NSDictionary*)dic{
    __block int length =  [dic allKeys].count;
    __block int idx = 0;
    __block NSMutableString *param = [[NSMutableString alloc] initWithString:@"\{"];
    [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        
        if([obj isKindOfClass:[NSNumber class]])
            [param appendFormat:@"\"%@\":%@",(NSString*)key, obj];
        else
            [param appendFormat:@"\"%@\":\"%@\"",(NSString*)key, obj];
        
        idx++;
        if (idx == length) {
            [param appendString:@"}"];
            *stop = YES;
        }
        else
        {
            [param appendString:@","];
        }
    }];
    
    return param;
}

/**
 *  字典转换成Model
 *
 *  @param model 要转换的对象
 */
- (void)toModel:(id)model
{
    if (self.count > 0)
    {
        NSEnumerator *keyEnumer = [self keyEnumerator];
        for (id key in keyEnumer)
        {
            NSString *propertyName = key;
            id propertyValue = [self valueForKey:propertyName];
            if (propertyValue == nil || propertyValue == [NSNull null])
                continue;
            
            if ([propertyValue isKindOfClass:[NSDictionary class]])
            {
                Class typeClass = typeNameWithClass([model class], propertyName);
                if (![typeClass isSubclassOfClass:[NSDictionary class]])
                {
                    id obj = [[typeClass alloc] init];
                    [propertyValue toModel:obj];
                    propertyValue = obj;
                }
            }
            else if ([propertyValue isKindOfClass:[NSArray class]])
            {
                if ([model respondsToSelector:@selector(classAtInsideOfObjectWithProperty:)])
                {
                    Class objClass = [model classAtInsideOfObjectWithProperty:propertyName];
                    if (objClass != Nil)
                    {
                        NSMutableArray *tempDict = [[NSMutableArray alloc] initWithCapacity:[propertyValue count]];
                        for (NSDictionary *dict in propertyValue)
                        {
                            id obj = [[objClass alloc] init];
                            [dict toModel:obj];
                            [tempDict addObject:obj];
                        }
                        if (tempDict.count > 0)
                            propertyValue = tempDict;
                    }
                    
                }
            }
            
            NSString *propertySetMethod = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] capitalizedString]
                                           ,[propertyName substringFromIndex:1]];
            SEL selector = NSSelectorFromString(propertySetMethod);
            if ([model respondsToSelector:selector])
            {
                [model setValue:propertyValue forKey:propertyName];
            }
        }
    }
}
/************************************附加方法************************************/

#define kAttributeType              "T"//变量类型
#define kAttributeVariable          "V"//变量名称
#define kAttributeSetter            "S"//set方法名称
#define kAttributeGetter            "G"//get方法名称

/**
 *  获取类中属性的类型
 *
 *  @param cls     类结构
 *  @param varName 属性名称
 *
 *  @return 类型
 */
Class typeNameWithClass(Class cls, NSString *varName)
{
    if (varName.length <= 0)
        return nil;
    
    unsigned int outCount, i;
    
    NSString *result;
    //从属性找
    while (cls != [NSObject class])
    {
        objc_property_t *propertys = class_copyPropertyList(cls, &outCount);
        for (i = 0; i < outCount; ++i)
        {
            objc_property_t property = propertys[i];
            
            unsigned int outAttribute;
            objc_property_attribute_t *attributes= property_copyAttributeList(property, &outAttribute);
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            NSString *variableName, *getMethodName, *setMethodName, *typeName;
            
            for (int j = 0; j < outAttribute; ++j)
            {
                objc_property_attribute_t attribute = attributes[j];
                NSString *value = [NSString stringWithFormat:@"%s", attribute.value];
                
                if (strcmp(attribute.name, kAttributeType) == 0)
                    typeName = [[value stringByReplacingOccurrencesOfString:@"@\"" withString:@""] stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                else if (strcmp(attribute.name, kAttributeVariable) == 0)
                    variableName = value;
                else if (strcmp(attribute.name, kAttributeSetter) == 0)
                    setMethodName = value;
                else if (strcmp(attribute.name, kAttributeGetter) == 0)
                    getMethodName = value;
            }
            
            if ((propertyName.length > 0 && [propertyName compare:varName options:NSCaseInsensitiveSearch] == NSOrderedSame)
                || (variableName.length > 0 && [variableName compare:varName options:NSCaseInsensitiveSearch] == NSOrderedSame)
                || (getMethodName.length > 0 && [getMethodName compare:varName options:NSCaseInsensitiveSearch] == NSOrderedSame))
            {
                result = typeName;
            }
            else
            {
                NSString *propertySetMethod = [NSString stringWithFormat:@"set%@%@:", [[varName substringToIndex:1] capitalizedString]
                                               ,[varName substringFromIndex:1]];
                if (setMethodName.length > 0 && [setMethodName compare:propertySetMethod options:NSCaseInsensitiveSearch] == NSOrderedSame)
                    result = typeName;
            }
            
            if (attributes)
                free(attributes);
            
            if (result.length > 0)
                break;
        }
        if (propertys)
            free(propertys);
        
        if (result.length > 0)
            break;
        
        cls = class_getSuperclass(cls);
    }
    
    return result.length > 0 ? NSClassFromString(result) : Nil;
}


@end

使用:

#import "NSDictionary+MS.h"


-(id)initWithNotifyInfo:(NSDictionary *)dic

{

    if (self=[super init]) {

        [dic toModel:self];

    }

    return self;

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值