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

来源:互联网 发布:淘宝神舟旗舰店 编辑:程序博客网 时间:2024/05/21 16:22
#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=[superinit]) {

        [dictoModel:self];

    }

    return self;

}



0 0