- 首先,看需求
#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 的實(shí)現(xiàn)(調(diào)用 method_A 控制臺(tái)打印出B)
- 好,怎么實(shí)現(xiàn)辙浑?
#import "MethodsSwizzlingClass.h"
#import <objc/runtime.h> // 添加runtime頭文件
@implementation MethodsSwizzlingClass
// 在load方法中交換method_A 和 method_B 的實(shí)現(xiàn)
+ (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");
}
當(dāng)調(diào)用method_A就打印出B了
MethodsSwizzlingClass *class = [[MethodsSwizzlingClass alloc] init];
[class method_A];
- too sample升略?naive?
其實(shí)呢冰抢,現(xiàn)在你已經(jīng)知道如何交換兩個(gè)方法的實(shí)現(xiàn)了松嘶,如果自己實(shí)現(xiàn)一個(gè)不知道什么方法和系統(tǒng)中的方法交換的話,那么不就可以頂替掉系統(tǒng)中的方法了嗎挎扰?而且你還可以在不需要知道系統(tǒng)方法源碼的情況下為其添加新功能翠订。怎么樣?驚不驚喜遵倦?意不意外尽超?嘻嘻嘻
- 舉一個(gè)典型的??
頁(yè)面跳轉(zhuǎn)后,打印出當(dāng)前ViewController的類名梧躺,這對(duì)于熟悉一份陌生代碼還是有幫助的似谁,能夠提高你的姿勢(shì)水平
- emmm傲绣,怎么實(shí)現(xiàn)?
- 首先巩踏,創(chuàng)建UIViewController的拓展類
- 然后呢秃诵,實(shí)現(xiàn)viewDidAppear的替代方法
- 最后,和viewDidAppear方法交換實(shí)現(xiàn)
#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
簡(jiǎn)單粗暴到?jīng)]朋友塞琼,先這樣吧