KVC 結合 Runtime 可以做非常多的事情。本文分享一個實用工具,能獲取類/對象的所有成員變量、屬性、方法及協議,並藉此實現字典轉模型的功能。
本質上就是 NSObject 的一個分類:
#import <Foundation/Foundation.h> @interface NSObject (YSRuntime) /** 返回當前類的屬性數組 */ + (NSArray *)ys_propertiesList; /** 返回當前類的成員變量數組 */ + (NSArray *)ys_ivarsList; /** 返回當前類的對象方法數組 */ + (NSArray *)ys_methodList; /** 返回當前類的協議數組 */ + (NSArray *)ys_protocolList; /** 使用字典創建當前類的對象 */ + (instancetype)ys_objectWithDictionary:(NSDictionary *)dictionary; /** 使用字典數組創建當前類的對象數組 */ + (NSArray *)ys_objectsWithDictionaryArray:(NSArray<NSDictionary *> *)dictArray; @end
最主要的能力來自 objc/runtime.h,這裡列舉了部分實現,起到拋磚引玉的作用:
#import "NSObject+YSRuntime.h" #import <objc/runtime.h> @implementation NSObject (YSRuntime) #pragma mark - 屬性數組 const char *propertiesKey = "ys.propertiesList"; + (NSArray *)ys_propertiesList { NSArray *result = objc_getAssociatedObject(self, propertiesKey); if (result != nil) { return result; } unsigned int count = 0; objc_property_t *list = class_copyPropertyList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = 0; i < count; i++) { objc_property_t pty = list[i]; const char *cName = property_getName(pty); NSString *name = [NSString stringWithUTF8String:cName]; [arrayM addObject:name]; } free(list); objc_setAssociatedObject(self, propertiesKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC); return objc_getAssociatedObject(self, propertiesKey); } #pragma mark - 私有方法,針對字典轉模型中的自定義屬性 const char *propertiesTypeKey = "ys.propertiesTypeKey"; + (NSArray<NSDictionary *> *)ys_propertiesAndTypeList { NSArray *result = objc_getAssociatedObject(self, propertiesTypeKey); if (result != nil) { return result; } unsigned int count = 0; objc_property_t *list = class_copyPropertyList([self class], &count); NSMutableArray<NSDictionary *> *arrayM = [NSMutableArray<NSDictionary *> array]; for (unsigned int i = 0; i < count; i++) { objc_property_t pty = list[i]; const char *cType = property_getAttributes(pty); NSString *typeStr = [NSString stringWithUTF8String:cType]; if([typeStr containsString:@"\",&"]){ NSRange typeRange = [typeStr rangeOfString:@"\",&"]; NSString *type = [typeStr substringWithRange:NSMakeRange(3, typeRange.location - 3)]; const char *cName = property_getName(pty); NSString *name = [NSString stringWithUTF8String:cName]; NSDictionary *dict = @{name:type}; [arrayM addObject:dict]; } } free(list); objc_setAssociatedObject(self, propertiesTypeKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC); return objc_getAssociatedObject(self, propertiesTypeKey); } #pragma mark - 成員變量數組 const char *ivarsKey = "ys.ivarsList"; + (NSArray *)ys_ivarsList { NSArray *result = objc_getAssociatedObject(self, ivarsKey); if (result != nil) { return result; } unsigned int count = 0; Ivar *list = class_copyIvarList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = 0; i < count; i++) { Ivar ivar = list[i]; const char *cName = ivar_getName(ivar); NSString *name = [NSString stringWithUTF8String:cName]; [arrayM addObject:name]; } free(list); objc_setAssociatedObject(self, ivarsKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC); return objc_getAssociatedObject(self, ivarsKey); } #pragma mark - 方法數組 + (NSArray *)ys_methodList { unsigned int count = 0; Method *list = class_copyMethodList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = 0; i < count; i++) { Method method = list[i]; SEL selector = method_getName(method); NSString *name = NSStringFromSelector(selector); [arrayM addObject:name]; } free(list); return arrayM.copy; } #pragma mark - 協議數組 + (NSArray *)ys_protocolList { unsigned int count = 0; __unsafe_unretained Protocol **list = class_copyProtocolList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = 0; i < count; i++) { Protocol *protocol = list[i]; const char *cName = protocol_getName(protocol); NSString *name = [NSString stringWithUTF8String:cName]; [arrayM addObject:name]; } free(list); return arrayM.copy; } #pragma mark - 字典 -> 當前類的對象 + (instancetype)ys_objectWithDictionary:(NSDictionary *)dictionary{ NSArray *list = [self ys_propertiesList]; NSArray<NSDictionary *> *propertyTypeList = [self ys_propertiesAndTypeList]; id obj = [self new]; for (NSString *key in dictionary) { if([list containsObject:key]){ if ([dictionary[key] isKindOfClass:[NSDictionary class]]){ for(NSDictionary *dict in propertyTypeList){ if([key isEqualToString: [NSString stringWithFormat:@"%@",dict.allKeys.firstObject]]){ NSString *classTypeStr = dict[key]; Class class = NSClassFromString(classTypeStr); id objChild = [class ys_objectWithDictionary:dictionary[key]]; [obj setValue:objChild forKey:key]; } } } else{ [obj setValue:dictionary[key] forKey:key]; } } } return obj; } @end
和 YYModel 一樣,如果對象的某個屬性是另一個自定義對象,同樣可以起到連續轉換的作用。但比較遺憾的是,若某個屬性是數組又加了泛型約束,目前還取不到這個數組的泛型約束——YYModel 也有類似問題,因此當屬性為數組時,需要手動指定數組裡元素的類型。希望各路高手看到後能不吝賜教。
最後附上一個有趣的小技巧,透過 ys_ivarsList 拿到所有成員變量再逐級訪問:
// 設置隨機顏色給Application的statusBar id bgStyle = [[UIApplication sharedApplication] valueForKeyPath:@"statusBar.backgroundView.style"]; [bgStyle setValue:[UIColor redColor] forKey:@"backgroundColor"];
// 修改高德地圖和logo UIImageView *imgV = [mapView valueForKey:@"logoImageView"]; imgV.image = nil; [mapView setValue:imgV forKey:@"logoImageView"];
這套工具能極大簡化字典轉模型的流程,也展示了 KVC 與 Runtime 強大的動態特性。