·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> IOS字典快速转换为Model模型

IOS字典快速转换为Model模型

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

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

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

首先是要添加对应的使用的头文件#import <objc/runtime.h>

然后添加下面几个方法

Model从字典中填充数据

/*
 *  从字典中填充数据
 */
-(int)reflectDataFromDictionary:(NSDictionary *)dic
{
    unsigned int useCount ,outCount;
    Ivar *ivars = class_copyIvarList([self class], &outCount);
    
    for (const Ivar *p = ivars; p < ivars + outCount; p++) {
        Ivar const ivar = *p;
        
        //获取变量名
        NSString *varName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        
        //获取变量值
        id varValue = [self valueForKey:varName];
        
        //如果是直接包含此名称的
        if ([dic.allKeys containsObject:varName]) {
            varValue = [dic objectForKey:varName];
            useCount++;
        }else{
            NSString *tmp_varName = [self removeFirstUnderlined:varName];
            if ([dic.allKeys containsObject:tmp_varName]) {
                varValue = [dic objectForKey:tmp_varName];
                useCount++;
            }
        }
        
        [self setValue:varValue forKey:varName];
    }
    
    return useCount;
}

两个辅助方法

/*
 *  移除掉第一个下划线
 */
-(NSString *)removeFirstUnderlined:(NSString *)str
{
    if ([[str substringToIndex:1] isEqual:@"_"]) {
        return [str substringFromIndex:1];
    }
    return str;
}

/*
 *  获取所有属性
 */
- (NSArray*)PRopertyKeys
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    free(properties);
    return keys;
}

将Model转换为字典

/*
 *  转换为字典
 */
-(NSDictionary *)convertToDictionary
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    for (NSString *key in [self propertyKeys]) {
        id propertyValue = [self valueForKey:key];
        [dic setObject:propertyValue forKey:key];
    }
    
    return dic;
} 

抽空写了一个Demo出来,GitHub死活上传不上去,所以放到CSDN上去了。如果需要的话可以Down下来看看http://download.csdn.net/detail/anxin1225/8190975

然后,就没有然后了……