標籤:
-
一般情況下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代碼