谢南峰子_老驴之------更换函数实现方法

勤能补拙之多敲出代码

// * Returns a specified instance method for a given class.
方法一:Method class_getInstanceMethod(Class cls, SEL name)

// * Returns the implementation of a method.
方法二:IMP method_getImplementation(Method m)

// * Returns a string describing a method's parameter and return types.
方法三:const char method_getTypeEncoding(Method m)

// * Adds a new method to a class with a given name and implementation.
方法四:BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)

// * Replaces the implementation of a method for a given class.
方法五:IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types) 

// * Exchanges the implementations of two methods.
方法六:void method_exchangeImplementations(Method m1, Method m2)


#import "Test.h"
#import <objc/runtime.h>

void SwizzleMethod(Class clazz, SEL origin, SEL current) {
    Method originMethod = class_getInstanceMethod(clazz, origin);
    Method currentMethod = class_getInstanceMethod(clazz, current);
    
    IMP originIMP = method_getImplementation(originMethod);
    IMP currentIMP = method_getImplementation(currentMethod);
    
    const char * originType = method_getTypeEncoding(originMethod);
    const char * currentType = method_getTypeEncoding(currentMethod);
    
    BOOL success = class_addMethod(clazz, origin, currentIMP, currentType);
    if (success) {
        class_replaceMethod(clazz, current, originIMP, originType);
    } else {
        method_exchangeImplementations(originMethod, currentMethod);
    }
}

@implementation Test
+ (void)load {
    SwizzleMethod([self class], @selector(method1), @selector(method2));
    SwizzleMethod([self class], @selector(method1), @selector(method3));
}

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

- (void)method2 {
    NSLog(@"b");
    [self method2];
}

- (void)method3 {
    NSLog(@"c");
    [self method3];
}

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    Test *text = [[Test alloc] init];
    [text method1];
    
    NSLog(@"---------------------");
    
    [text method2];
    
    NSLog(@"---------------------");
    
    [text method3];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文:李理 昨天去超市买菜的时候,路过一家鲜花店,门口的黑板上用漂亮的...
    李理joke阅读 4,365评论 5 2
  • 比起竞选失败,我更伤心的是你的冷漠…… 或许你眼界真的好高,高到你连瞧都不瞧我…… 我想起了张爱玲的那句话:遇到了...
    送你一首狂想曲阅读 891评论 0 0
  • 1践行。 作者举例是购买GAFATA的股票,1月1日推荐了这几个股票。有人买了,有人没有买。 印象最深的是这样一句...
    medman阅读 1,482评论 0 0