【iOS开发】手把手教你用runtime替换掉类中现有的方法

  • 首先,看需求
#import <Foundation/Foundation.h>

@interface MethodsSwizzlingClass : NSObject

- (void)method_A;

- (void)method_B;

@end
#import "MethodsSwizzlingClass.h"

@implementation MethodsSwizzlingClass

- (void)method_A {
    NSLog(@"A");
}

- (void)method_B {
    NSLog(@"B");
}

@end

需求:交换 method_A 和 method_B 的实现(调用 method_A 控制台打印出B)

  • 好,怎么实现?
#import "MethodsSwizzlingClass.h"
#import <objc/runtime.h> // 添加runtime头文件

@implementation MethodsSwizzlingClass

// 在load方法中交换method_A 和 method_B 的实现
+ (void)load {
    Method originMethod = class_getInstanceMethod([MethodsSwizzlingClass class], @selector(method_A));
    Method replaceMethod = class_getInstanceMethod([MethodsSwizzlingClass class], @selector(method_B));
    method_exchangeImplementations(originMethod, replaceMethod);
}

- (void)method_A {
    NSLog(@"A");
}

- (void)method_B {
    NSLog(@"B");
}

当调用method_A就打印出B了

MethodsSwizzlingClass *class = [[MethodsSwizzlingClass alloc] init];
[class method_A];
  • too sample?naive?

其实呢,现在你已经知道如何交换两个方法的实现了,如果自己实现一个不知道什么方法和系统中的方法交换的话,那么不就可以顶替掉系统中的方法了吗?而且你还可以在不需要知道系统方法源码的情况下为其添加新功能。怎么样?惊不惊喜?意不意外?嘻嘻嘻

  • 举一个典型的🌰

页面跳转后,打印出当前ViewController的类名,这对于熟悉一份陌生代码还是有帮助的,能够提高你的姿势水平

  • emmm,怎么实现?
    • 首先,创建UIViewController的拓展类
    • 然后呢,实现viewDidAppear的替代方法
    • 最后,和viewDidAppear方法交换实现
#import "UIViewController+log.h"
#import <objc/runtime.h>

@implementation UIViewController (log)

+ (void)load {
    Method originMethod = class_getInstanceMethod([self class], @selector(viewDidAppear:));
    Method replaceMethod = class_getInstanceMethod([self class], @selector(viewDidAppear_huang:));
    method_exchangeImplementations(originMethod, replaceMethod);
}

- (void)viewDidAppear_huang:(BOOL)animated {
    [self viewDidAppear_huang:animated];
    NSLog(@"current class ---> %@", NSStringFromClass([self class]));
}

@end

简单粗暴到没朋友,先这样吧

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

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,898评论 18 399
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,805评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 6,572评论 0 7
  • 《血战钢锯岭》这部影片为人们呈现了信仰的奇迹。当放映厅灯亮,曲终人散,在这奇迹的背后,我又感到了宽容的力量。 戴斯...
    桃之夭夭的世界阅读 2,669评论 0 1