runtime方法的替换

首先甩出苹果官方文档的链接https://developer.apple.com/reference/objectivec/1418769-method_exchangeimplementations?language=objc

苹果为运行时交换方法提供了两种方法,如下
先创建一个类(eg:TestClass)
在.h文件里面声明两个方法

#import <Foundation/Foundation.h>

@interface TestClass : NSObject

- (void)testMethod1;

- (void)testMethod2;

@end

在.m文件里面实现两个方法

#import "TestClass.h"

@implementation TestClass

- (void)testMethod1{

    NSLog(@"这是测试类的实例方法---1");
}

- (void)testMethod2{

    NSLog(@"这是测试类的实例方法+++2");
}

@end

注意:testMethod1打印的是 @”这是测试类的实例方法—1”
testMethod2打印的是 @”这是测试类的实例方法+++2”


第一种运行时交换方法的方法

void method_exchangeImplementations(Method m1, Method m2);
- (void)firstExchangeMethod {

    TestClass *test = [[TestClass alloc]init];

    [test testMethod1];

    NSLog(@"----------交换方法前后的分割线----------");

    Method T1 = class_getInstanceMethod([TestClass class], @selector(testMethod1));

    Method T2 = class_getInstanceMethod([TestClass class], @selector(testMethod2));

    method_exchangeImplementations(T1, T2);

    [test testMethod1];
}

打印结果如图:
这里写图片描述


第二种运行时交换方法的方法:

IMP imp1 = method_getImplementation(m1);
IMP imp2 = method_getImplementation(m2);
method_setImplementation(m1, imp2);
method_setImplementation(m2, imp1);
- (void)secondExchangeMethod{

    TestClass *test = [[TestClass alloc]init];

    [test testMethod1];

    NSLog(@"----------交换方法前后的分割线----------");

    Method m1 = class_getInstanceMethod([TestClass class], @selector(testMethod1));
    Method m2 = class_getInstanceMethod([TestClass class], @selector(testMethod2));

    IMP imp1 = method_getImplementation(m1);
    IMP imp2 = method_getImplementation(m2);

    method_setImplementation(m1, imp2);
    method_setImplementation(m2, imp1);

    [test testMethod1];

}

打印结果如下:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值