IOS 字典快速轉換為Model 模型


一般情況下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

然后,就沒有然后了……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM