福利->KVC+Runtime获取类/对象的属性/成员变量/方法/协议并实现字典转模型

时间:2022-06-10 11:47:37

我们知道,KVC+Runtime可以做非常多的事情。有了这个,我们可以实现很多的效果。

这里来个福利,利用KVC+Runtime获取类/对象的所有成员变量、属性、方法及协议;

并利用它来实现字典转模型。

废话不多说,直接上代码:

1、工具类(其实就是NSObject的一个分类)头文件

 #import <Foundation/Foundation.h>

 @interface NSObject (YSRuntime)

 /**
返回当前类的属性数组 @return 属性数组(如:"name","age","address")
*/
+ (NSArray *)ys_propertiesList; /**
返回当前类的成员变量数组 @return 成员变量数组
*/
+ (NSArray *)ys_ivarsList; /**
返回当前类的对象方法数组 @return 方法数组
*/
+ (NSArray *)ys_methodList; /**
返回当前类的协议数组 @return 协议数组
*/
+ (NSArray *)ys_protocolList; /**
使用字典创建当前类的对象 @param dictionary 字典 @return 当前类的对象
*/
+ (instancetype)ys_objectWithDictionary:(NSDictionary *)dictionary; /**
使用字典数组创建当前类的对象数组 @param dictArray 字典数组 @return 当前类的对象数组
*/
+ (NSArray *)ys_objectsWithDictionaryArray:(NSArray<NSDictionary *> *)dictArray; @end

2、下面我们来实现里面的方法,以后就用它来获取类/对象的属性、成员变量、方法和协议

说明一下:最主要的方法是在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 = ;
objc_property_t *list = class_copyPropertyList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = ; 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 - 私有方法,专门针对字典转模型中的自定义属性,{@"name":@"Dog"},name是属性名,Dog是自定义的模型类,属性名-属性类型
const char *propertiesTypeKey = "ys.propertiesTypeKey";
+ (NSArray<NSDictionary *> *)ys_propertiesAndTypeList { // 获取关联对象
NSArray *result = objc_getAssociatedObject(self, propertiesTypeKey); if (result != nil) {
return result;
} unsigned int count = ;
objc_property_t *list = class_copyPropertyList([self class], &count); NSMutableArray<NSDictionary *> *arrayM = [NSMutableArray<NSDictionary *> array]; for (unsigned int i = ; 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(, typeRange.location - )]; 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 = ;
Ivar *list = class_copyIvarList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = ; 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 = ;
Method *list = class_copyMethodList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = ; 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 = ;
__unsafe_unretained Protocol **list = class_copyProtocolList([self class], &count); NSMutableArray *arrayM = [NSMutableArray array]; for (unsigned int i = ; 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 if([dictionary[key] isKindOfClass:[NSArray<NSDictionary *> class]]){ // 属性值为字典数组 }
else{
[obj setValue:dictionary[key] forKey:key];
}
}
} return obj;
} #pragma mark - 字典数组 -> 当前类的对象数组
+ (NSArray *)ys_objectsWithDictionaryArray:(NSArray<NSDictionary *> *)dictArray { if (dictArray.count == ) {
return nil;
} // 当前类的属性数组
NSArray *list = [self ys_propertiesList]; NSArray<NSDictionary *> *propertyTypeList = [self ys_propertiesAndTypeList]; NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dictionary in dictArray) { 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 if([dictionary[key] isKindOfClass:[NSArray<NSDictionary *> class]]){ // 属性值为字典数组 }
else{
[obj setValue:dictionary[key] forKey:key];
}
}
} [arrayM addObject:obj];
} return arrayM.copy;
} @end

3、和YYModel一样,如果对象的一个属性为另一个自定义对象,那么同样可以起到连转的作用;

4、但比较遗憾的是,也是和YYModel一样,如果有一个属性是数组,又添加了泛型约束,没有取到这个数组的泛型约束。

我记得,YYModel就有这个问题,因为取不到泛型约束,所以当有属性为数组的时候,需要手动指定数组里面的元素类型。

希望各位大神看到后不吝赐教。

5、最后贴出一个小且非常有趣的小东东,里面的key就是我用上面的 “ys_ivarsList” 获取到所有成员变量,然后一级一级找的^_^

     // 设置随机颜色给Application的statusBar,从此妈妈再也不用担心statusBar的背景色
id bgStyle = [[UIApplication sharedApplication] valueForKeyPath:@"statusBar.backgroundView.style"];
[bgStyle setValue:[UIColor redColor] forKey:@"backgroundColor"];
     // frame = (5 649; 55 13)
// 修改高德地图和logo,删除和替换自己随意定
UIImageView *imgV = [mapView valueForKey:@"logoImageView"]; // 这就就是高德地图的logo
imgV.image = nil; // 我们把imageView的图片置为nil
[mapView setValue:imgV forKey:@"logoImageView"]; // 哈哈,这个高德地图的logo就不见了,妈妈从此再也不需要担心logo了