RunTime运行时之动态替换和改变方法实现

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

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //获取方法所有名
    [self getMethodName];
    //添加方法
    [self addMethod];
    //替换方法
    [self changeMethod];
    //改变方法实现
    [self changeMethodImpl];
    //方法实现改变后调用实验
    [self method_1];
}

#pragma 获取方法名
- (void)getMethodName{
    void (*useMethod)(id,SEL);
    unsigned int outCount = 0;
    Method *methods = class_copyMethodList([self class], &outCount);
    for(int i = 0;i < outCount;i++){
        Method method = methods[i];
        SEL sel = method_getName(method);
        NSLog(@"%s",sel_getName(sel));
        if(sel == @selector(method_1)){
            useMethod = (void (*)(id,SEL))[self methodForSelector:sel];
            useMethod(self,sel);
        }
    }
}

#pragma 添加方法
- (void)addMethod{
    class_addMethod([self class], @selector(method::), (IMP)method_impl, "i@:i@");
    //此时调用方法需要用performSelector,否则编译器会报错
    [self performSelector:@selector(method::) withObject:@[@"piaojin",@(25)]];
}

#pragma 动态替换方法(也可以用于替换方法实现)
- (void)changeMethod{
//method_1与method_2进行替换
    method_exchangeImplementations(class_getInstanceMethod([self class], @selector(method_1)), class_getInstanceMethod([self class], @selector(method_2)));
}

#pragma 动态替换方法实现
- (void)changeMethodImpl{
//改变method_1的实现为method_3
    class_replaceMethod([self class], @selector(method_1), (IMP)method_3, "");
}

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

void method_impl(id self,SEL _cmd,NSString *str,int age){
    NSLog(@"str:%@,age:%d",str,age);
}

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

void method_3(){
    NSLog(@"method_3");
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于IoC容器和控制反转(也被称为依赖注入)模式以及Spring IoC的应用场景我在这里就不进行赘述了,下面直接...
    EakonZhao阅读 8,379评论 0 21
  • 今天给一个客户打回访电话 他的声音特别像你 口音一模一样 他是你的老乡 但他却不是你 最近咋样 和新女友感情如何 ...
    TOJECO阅读 1,625评论 0 0
  • 具体原理一句两句也说不清楚,网络文章: http://www.cnblogs.com/skywang12345/p...
    鱼仔_1625阅读 1,456评论 0 0
  • 【2017年10月7日-007-12】 ——读《战胜华尔街》每周小结week5 彼得.林奇作为一个著名的基金管理人...
    dream2024阅读 4,162评论 0 4
  • 我不是博文强识的学者,不是文采飞扬的作家,也没有好的文笔,没有华丽的词藻, 我来这里,只是想用简单的话语,去记录我...
    水墨青花e阅读 1,605评论 0 1