在 iOS 的介面開發中,一個常見的做法是先建立對應的 Model,再透過 Nib 檔案與 Model 進行關聯,如此一來便能輕鬆取得 Nib 上各個控件的實例,進而快速完成頁面的組裝。
然而原生架構並不支援直接從 JSON 產生 Model,網路請求回傳的資料往往只是一個個字典。要把這些字典轉換成方便操作的 Model 物件,就必須借助 Objective-C 的 Runtime 機制。以下示範如何透過「鍵值編碼(KVC)」搭配 Runtime 的屬性枚舉,完成字典到 Model、以及 Model 到字典的雙向轉換。
核心思路是:利用 class_copyPropertyList 取得當前類別的所有屬性,逐一比對字典中是否存在同名鍵,若存在則透過 KVC 賦值。當遇到巢狀的 NSDictionary 時,會遞迴建立對應的子物件。
-(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;
}
為了解析屬性類型並動態建立實例,需要另外兩個輔助方法:一個負責從屬性描述字串中擷取類別名稱,另一個則依類別名稱透過 NSBundle 建立對應的物件實例。
-(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;
}
反向操作同樣簡單,只要遍歷所有屬性鍵,逐一透過 KVC 取值並組裝成字典即可。
-(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;
}
透過這套機制,開發者就能在字典與 Model 之間自由轉換,大幅簡化網路資料的解析與封裝流程。