【objective-c】字典快速轉換為Model代碼

來源:互聯網
上載者:User

標籤:

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

 

【objective-c】字典快速轉換為Model代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.