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

2017-09-14  本文已影响13人  Huangbaoqin
#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];

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

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

#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

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

上一篇下一篇

猜你喜欢

热点阅读