- 首先,看需求
#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
簡單粗暴到沒朋友,先這樣吧