Runtime之强行调用被覆盖类中的方法

1.关于类别覆盖原有类方法后,我们任然要想调用其原有类的方法。所用的底层转换方式

#import <Foundation/Foundation.h>
#import "CFRuntimeKit.h"
#import "CFPerson.h"
#import "CFPerson+Category1.h"
#import "CFPerson+Category2.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        CFPerson *person = [[CFPerson alloc]init];
        //方法覆盖问题验证(后面编译的分类方法在最前面,优先访问它)
        [person eating];
        //查看方法列表
        NSArray *methodArr = [CFRuntimeKit fetchMethodList:[CFPerson class]];
        NSLog(@"methodArr:%@",methodArr);
        
        /*
         *调用person类的eating方法
         */
        unsigned int outCount = 0;
        Method *methodList = class_copyMethodList([CFPerson class], &outCount);
        IMP lastImp = NULL;
        SEL lastSel = NULL;
        for (unsigned int i=0; i<outCount; i++) {
            Method method = methodList[i];
            SEL methodSEL = method_getName(method);
            NSString *methodName =[NSString stringWithUTF8String:sel_getName(methodSEL)];
            if ([methodName isEqualToString:@"eating"]) {
                lastImp = method_getImplementation(method);
                lastSel = method_getName(method);
            }
        }
        ((void (*)(id,SEL))(void *)lastImp)(person,lastSel);
        free(methodList);
    }
    
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 她去拿快递。 到了之后发现有个男生也在,男生问她, “汇通?” 上铺以为他是工作人员,眼睛亮亮的,点头“嗯,汇通!...
    小梨花阅读 259评论 0 0
  • 刘琳坚持第299天原创分享(2018/3/24) 昨天做了一个特别不好的梦,在梦里,我失去了最在乎的。在...
    小溪与大海阅读 268评论 2 3