在項(xiàng)目中有時(shí)會(huì)遇到自己寫(xiě)的分類(lèi)和其他分類(lèi)方法命名一樣巡李,導(dǎo)致自己分類(lèi)的方法不執(zhí)行問(wèn)題鉴嗤,所以寫(xiě)了一個(gè)類(lèi)檢查項(xiàng)目中有無(wú)category重復(fù)方法名問(wèn)題
#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;
/** 獲得方法數(shù)組*/
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 重復(fù)方法 class = %@ method = %@",cls,methodName);
}
[methodNames addObject:methodName];
}
/** 釋放(因?yàn)槭荂語(yǔ)言函數(shù)歧譬,所以需要手動(dòng)的內(nèi)存管理退子,釋放內(nèi)存)*/
free(methodList);
}