在项目中有时会遇到自己写的分类和其他分类方法命名一样,导致自己分类的方法不执行问题,所以写了一个类检查项目中有无category重复方法名问题
#import <objc/runtime.h>
#import <dlfcn.h>
#import <mach-o/ldsyms.h>
@implementation CheckCategoryMethod
+ (void)checkCategoryRepeatMethod{
NSArray*allClassesInfo = [[self class] bundleAllClassesInfo];
for(NSString* clsName in allClassesInfo) {
[[self class] printRepeatMethodNamesOfClass:NSClassFromString(clsName)];
}
}
+ (NSArray <NSString *> *)bundleAllClassesInfo {
NSMutableArray *resultArray = [NSMutableArray new];
intclassCount =objc_getClassList(NULL,0);
Class*classes =NULL;
classes = (__unsafe_unretainedClass*)malloc(sizeof(Class) *classCount);
classCount =objc_getClassList(classes, classCount);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_apply(classCount, dispatch_get_global_queue(0, 0), ^(size_t index) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
Classclass = classes[index];
NSString*className = [[NSString alloc]initWithUTF8String:class_getName(class)];
[resultArray addObject:className];
dispatch_semaphore_signal(semaphore);
});
free(classes);
return resultArray.mutableCopy;
}
+ (void)printRepeatMethodNamesOfClass:(Class)cls{
unsigned int count;
/** 获得方法数组*/
Method*methodList =class_copyMethodList(cls, &count);
NSMutableArray *methodNames = [[NSMutableArray alloc] init];
for(inti =0; i < count; i++) {
Methodmethod = methodList[i];
NSString*methodName =NSStringFromSelector(method_getName(method));
if([methodNames containsObject:methodName]){
NSLog(@"category 重复方法 class = %@ method = %@",cls,methodName);
}
[methodNames addObject:methodName];
}
/** 释放(因为是C语言函数,所以需要手动的内存管理,释放内存)*/
free(methodList);
}