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