ios Category同名函数情况下调用原函数

当分类跟原来的类中有同名函数时,因为在类的结构中的函数列表中,分类的函数会在原类函数的前面,执行函数调用时,先找到分类函数就直接执行了,不再往后寻找到原来函数执行。
这个情况下,如果想要执行原类中的函数,需要倒序寻找函数列表中的函数来执行。代码如下:
导入运行时

#import <objc/runtime.h>

实现原类中函数调用

+(void)performMethod:(Class)theClass
      isClassMethod:(BOOL)isClassMethod
           selector:(SEL)selector{
    
    
    
   
    if (isClassMethod){
    
     //类函数 在元类里面放了方法列表(而不是在类中的方法列表)
        theClass = objc_getMetaClass(object_getClassName(theClass));
    }
    unsigned int count = 0;
    Method *methods = class_copyMethodList(theClass,&count);
    
    for(unsigned int index = count; index ; index--) {
    
    
        Method method = methods[index];
        if (strcmp(sel_getName(method_getName(method)), sel_getName(selector)) == 0 ) {
    
    
            void(*imp)(id, SEL) = (void(*)(id, SEL))method_getImplementation(method);
            imp(theClass, selector);
            break;
        }
    }
}

举个例子,下面就没有重复写上面那个函数了,调用分类函数里面又调用原函数

TestRumTime.m:

#import "TestRumTime.h"
#import <objc/runtime.h>
@implementation TestRumTime

-(void)method1{
    
    
    NSLog(@"method1");
}

@end

@implementation TestRumTime (test)

-(void)method1 {
    
    
    NSLog(@"调用了 分类函数method1");
    [TestRumTime performMethod:[TestRumTime class] isClassMethod:NO selector:_cmd];

}
@end

然后调用一下函数

[[TestRumTime new] method1];

打印出来就这样
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/htwhtw123/article/details/128728288