既然是一個程序猿,就要不斷的學習,雖然沒有地位,但是為了家庭,你說要不要生活,哎,算了,開始說我們的話題吧,
Method Swizling --動態交換IMP實現指針
在OC中調用一個方法,其實并不是方法,而是找到內存地址的一個字符串地址,查找是根據@selector 關鍵字而來的,利用Objective-C的動態特性,可以實現在運行時偷換selector 對應的方法實現,從而達到給方法掛鉤的目的
每個類都有一個方法列表,存放著selector的方法和名字實現的映射關系,
IMP 也可以理解為OC中的implements 指針實現。
我們常用的動態交換方法有系統提供給我們幾個方法
1. method_exchangeImplementations 交換兩個方法
2. class_replaceMethod 替換方法
3. method_setImplementation 設置實現方法
看到上面的圖,我們是否可以想到兩個指針交換數據,我們不能簡單的交換指針名字,而是交換了指針地址
對于這一塊的東西理解的也是毛坯,等有時間繼續了解一下,目前我根據我看到的資料,分享一下簡單的使用
我們來獲取控制器的viewdidload 方法 viewWillAppear 出現的次數,我們進行動態的交換方法,
我們先寫一個動態交換方法
第一步,我們新建一個Category ,名字為 UIViewController+AOP
我們來寫一個靜態實例交換方法
//originalSelector 原來方法
// swizzleSelector 動態運行時的交換方法
void swizzleMethod(Class class,SEL originalSelector,SEL swizzleSelector){
//class_getInstanceMethod返回 class的名稱為selector的方法
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzleSelector);
//method_getImplementation 返回method的實現指針
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if(didAddMethod){
//class_replaceMethod 替換函數實現 函數 originalMethod 用swizzleSelector 替換
class_replaceMethod(class, swizzleSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
//交換兩個IMP是實現指針
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
以上都有注釋,這里就不多寫明了,下面我們看下系統提供的交換方法的API,
// 交換兩個方法,傳入的參數是兩個@selector 方法
OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
//替換方法
參數含義
Class class : 需要替換方法的類名
SEL name : 需要替換的方法名字
IMP imp : 需要實現的方法名字
const char * types :原方法的名字
OBJC_EXPORT IMP class_replaceMethod(Class cls, SEL name, IMP imp,
const char *types)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
//設置實現指針
參數 :
Method m: 方法名字
IMP imp : 實現指針
OBJC_EXPORT IMP method_setImplementation(Method m, IMP imp)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
為什么我們要這么麻煩寫這么一段代碼,接手維護的項目大多都不好管理,需要進行重構,我們盡可能的會用少量的代碼簡化我的方法體
下面我們繼續實現類中一定會調用的方法load 方法
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
swizzleMethod(class, @selector(viewDidLoad), @selector(aop_viewDidLoad:));
swizzleMethod(class, @selector(viewDidAppear:), @selector(aop_viewDidAppear:));
swizzleMethod(class, @selector(viewWillAppear:), @selector(aop_viewWillAppear:));
swizzleMethod(class, @selector(viewWillDisappear:), @selector(aop_viewWillDisAppear:));
});
}
問題:+(void)load VS +(void)initialize
每個類的這兩個方法都會被Objective-C運行時系統自動調用,+load 方法是在一個類最開始調用的,+initialize 是在應用中第一次調用該類或者他的實例的方式之前調用,這兩個方法都可以使用,只有實現了才會被執行,
既然是分類,就會全局監聽,+load 能夠保證在類初始化的時候會被加載,通過這個操作可以做一些統一的操作,但是+initialize 并不能保證什么時候被調用,有可能永遠也不會被調用,如果應用程序從未直接給該類發送任何消息,則無法調用
在調用load 方法的時候,我們通常是通過
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
//我們采取了一個預防措施,防止運行時多次被執行,確保代碼即使使用在多線程環境下也只會被執行一次,我們優先使用GCD
});
調用_cmd
下面這段代碼不會影響執行,也不會進入死循環,
aop_viewWillAppear 這個方法會在運行時進入到協同的viewWillAppear 方法執行,但是我們不能在這個里面調用viewWillAppear,以免造成無法控制的危險
- (void)aop_viewWillAppear:(BOOL)animated{
[self aop_viewWillAppear:animated];
NSLog(@"111111111111");
}
下面我們給出源代碼整體的實現思路,
#import <UIKit/UIKit.h>
@interface UIViewController (AOP)
- (void)aop_viewWillAppear:(BOOL)animated;
- (void)aop_viewDidAppear:(BOOL)animated;
- (void)aop_viewDidLoad:(BOOL)animated;
- (void)aop_viewWillDisAppear:(BOOL)animated;
@end
#import "UIViewController+AOP.h"
#import <objc/runtime.h>
@implementation UIViewController (AOP)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
swizzleMethod(class, @selector(viewDidLoad), @selector(aop_viewDidLoad:));
swizzleMethod(class, @selector(viewDidAppear:), @selector(aop_viewDidAppear:));
swizzleMethod(class, @selector(viewWillAppear:), @selector(aop_viewWillAppear:));
swizzleMethod(class, @selector(viewWillDisappear:), @selector(aop_viewWillDisAppear:));
});
}
void swizzleMethod(Class class,SEL originalSelector,SEL swizzleSelector){
//class_getInstanceMethod返回 class的名稱為selector的方法
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzleSelector);
//method_getImplementation 返回method的實現指針
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if(didAddMethod){
//class_replaceMethod 替換函數實現 函數 originalMethod 用swizzleSelector 替換
class_replaceMethod(class, swizzleSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
//交換兩個IMP是實現指針
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void)aop_viewWillAppear:(BOOL)animated{
[self aop_viewWillAppear:animated];
NSLog(@"111111111111");
}
- (void)aop_viewDidAppear:(BOOL)animated{
[self aop_viewDidAppear:animated];
NSLog(@"22222222222");
}
- (void)aop_viewDidLoad:(BOOL)animated{
[self aop_viewDidLoad:animated];
NSLog(@"33333333333333");
if([self isKindOfClass:[UINavigationController class] ]){
UINavigationController * nav =(UINavigationController *)self;
nav.navigationBar.translucent = NO;
nav.navigationBar.tintColor = [UIColor whiteColor];
nav.navigationBar.barTintColor = [UIColor greenColor];
NSDictionary * titleAtt = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
[[UINavigationBar appearance]setTitleTextAttributes:titleAtt];
[[UIBarButtonItem appearance ] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
}
self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
}
- (void)aop_viewWillDisAppear:(BOOL)animated{
[self aop_viewWillDisAppear:animated];
#ifndef DEBUG
NSLog(@"44444444");
#endif
}
@end
以上是整體的代碼
這種方法可以來控制我們的代碼減少代碼結構,
文章如有錯誤還望大神給予指正,在這里只是學習一下,
iOS 學習交流群:392633290 加群備注:(簡書)
Apple 官方的 Objective-C Runtime Reference objc/runtime
同時附上原文鏈接:
OC動態運行時使用Method Swizling