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

IOS 字典快速转换为Model

时间:2014-08-21 11:24:03      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   文件   for   ar   

一般情况下IOS得局部页面加载的过程是,创建一个Model然后,将Nib文件与Model进行关联,然后能够快速的获取到Nib文件上的控件实例。操作生成页面。

但是原生的内容是没有直接通过Json获取Model只能生成字典。然后转换为Model。下列方法就是通过字典来转换为Model的过程。

 

将字典转换为Model

-(BOOL)reflectDataFromOtherObject:(NSDictionary *)dic
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        NSString *propertyType = [[NSString alloc] initWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
        
        if ([[dic allKeys] containsObject:propertyName]) {
            id value = [dic valueForKey:propertyName];
            if (![value isKindOfClass:[NSNull class]] && value != nil) {
                if ([value isKindOfClass:[NSDictionary class]]) {
                    id pro = [self createInstanceByClassName:[self getClassName:propertyType]];
                    [pro reflectDataFromOtherObject:value];
                    [self setValue:pro forKey:propertyName];
                }else{
                    [self setValue:value forKey:propertyName];
                }
            }
        }
    }
    
    free(properties);
    return true;
}

其他两个辅助类型方法

-(NSString *)getClassName:(NSString *)attributes
{
    NSString *type = [attributes substringFromIndex:[attributes rangeOfRegex:@"\""].location + 1];
    type = [type substringToIndex:[type rangeOfRegex:@"\""].location];
    return type;
}

-(id) createInstanceByClassName: (NSString *)className {
    NSBundle *bundle = [NSBundle mainBundle];
    Class aClass = [bundle classNamed:className];
    id anInstance = [[aClass alloc] init];
    return anInstance;
}

 

将Model转换为字典

-(NSDictionary *)convertModelToDictionary
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    for (NSString *key in [self propertyKeys]) {
        id propertyValue = [self valueForKey:key];
        //该值不为NSNULL,并且也不为nil
        [dic setObject:propertyValue forKey:key];
    }
    
    return dic;
}

 

IOS 字典快速转换为Model,布布扣,bubuko.com

IOS 字典快速转换为Model

标签:style   blog   color   os   io   文件   for   ar   

原文地址:http://www.cnblogs.com/anxin1225/p/3926542.html

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