在Objective-C里調(diào)用一個(gè)方法是這樣的:
[object method];
編譯器會(huì)把它翻譯成:
id objc_msgSend(object, selector,arg1,arg2,...)
id
id的定義:
/// A pointer to an instance of a class.
typedef struct objc_object *id;
/// Represents an instance of a class.
struct objc_object {
Class _Nonnull isa OBJC_ISA_AVAILABILITY;
};
objc_object結(jié)構(gòu)體里的成員變量isa指向了實(shí)例對(duì)象的類(lèi)對(duì)象。
Class
Class的定義:
typedef struct objc_class *Class;
struct objc_class {
Class _Nonnull isa OBJC_ISA_AVAILABILITY;
#if !__OBJC2__
Class _Nullable super_class OBJC2_UNAVAILABLE;
const char * _Nonnull name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list * _Nullable ivars OBJC2_UNAVAILABLE;
struct objc_method_list * _Nullable * _Nullable methodLists OBJC2_UNAVAILABLE;
struct objc_cache * _Nonnull cache OBJC2_UNAVAILABLE;
struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE;
#endif
} OBJC2_UNAVAILABLE;
objc_class結(jié)構(gòu)體里的成員變量isa指向了類(lèi)的元類(lèi);成員變量super_class指向了類(lèi)的父類(lèi)。
類(lèi)也是對(duì)象,可以看做是元類(lèi)的實(shí)例,元類(lèi)里的方法列表存儲(chǔ)的是類(lèi)方法。
SEL
SEL的定義:
typedef struct objc_selector *SEL;
runtime的源碼里沒(méi)有給出objc_selector的定義。SEL類(lèi)型是方法的selector,可以理解為區(qū)分方法的 ID。其實(shí)它就是個(gè)映射到方法的C字符串,你可以用 Objc 編譯器命令 @selector() 或者 Runtime 系統(tǒng)的 sel_registerName 函數(shù)來(lái)獲得一個(gè) SEL 類(lèi)型的方法選擇器。
objc_cache
類(lèi)有一個(gè)存放方法的方法列表和一個(gè)存放緩存方法的哈希表。objc_msgSend
這個(gè)函數(shù)的內(nèi)部是現(xiàn)實(shí)是先從類(lèi)的緩存哈希表里尋找方法,如果沒(méi)找到,則從類(lèi)的方法列表里尋找,找到后會(huì)將方法填充到緩存哈希表里。
runtime源碼
objc_msgSend的源碼解析
類(lèi)的方法的緩存解析
消息轉(zhuǎn)發(fā)
objc在向一個(gè)對(duì)象發(fā)送消息時(shí),runtime庫(kù)會(huì)根據(jù)對(duì)象的isa指針找到該對(duì)象實(shí)際所屬的類(lèi)對(duì)象,然后在該類(lèi)對(duì)象中的方法列表以及其父類(lèi)方法列表中尋找方法運(yùn)行,如果,在最頂層的父類(lèi)中依然找不到相應(yīng)的方法時(shí),程序在運(yùn)行時(shí)會(huì)掛掉并拋出異常unrecognized selector sent to XXX 。但是在這拋出異常之前,objc的運(yùn)行時(shí)會(huì)給出三次拯救程序崩潰的機(jī)會(huì):
Dynamic Method resolution
首先會(huì)調(diào)用所屬類(lèi)的類(lèi)方法+resolveInstanceMethod:(實(shí)例方法)或者+resolveClassMethod:(類(lèi)方法)。在這個(gè)方法中,我們有機(jī)會(huì)為該未知消息新增一個(gè)”處理方法””。不過(guò)使用該方法的前提是我們已經(jīng)實(shí)現(xiàn)了該”處理方法”,只需要在運(yùn)行時(shí)通過(guò)class_addMethod函數(shù)動(dòng)態(tài)添加到類(lèi)里面就可以了。如下代碼所示:
void dynamicMethodIMP(id self, SEL _cmd) {//至少要有兩個(gè)參數(shù)self 和 _cmd.
// implementation ....
}
@implementation MyClass
+ (BOOL)resolveInstanceMethod:(SEL)aSEL
{
if (aSEL == @selector(resolveThisMethodDynamically)) {
class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:");
return YES;
}
return [super resolveInstanceMethod:aSEL];
}
@end
不過(guò)這種方案更多的是為了實(shí)現(xiàn)@dynamic屬性:
@interface MyClass : NSObject
@property (nonatomic, copy) NSString *name;
@end
#import "MyClass.h"
#import <objc/runtime.h>
NSString * dynamicNameIMP(id self, SEL _cmd)
{
NSString * name = objc_getAssociatedObject(self, _cmd);
return name;
}
void dynamicSetNameIMP(id self, SEL _cmd, NSString *name)
{
objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY);
}
@implementation MyClass
@dynamic name;
+ (BOOL)resolveInstanceMethod:(SEL)sel{
if (sel == @selector(name)) {
class_addMethod([self class], sel, (IMP)dynamicNameIMP, "v@:");
}
if (sel == @selector(setName:)) {
class_addMethod([self class], sel, (IMP)dynamicSetNameIMP, "v@:@");
}
return [super resolveInstanceMethod:sel];
}
@end
如果使用class_addMethod
添加類(lèi)方法,則class_addMethod
的第一個(gè)參數(shù)要傳入一個(gè)元類(lèi)對(duì)象object_getClass(self)
。
Fast forwarding
如果在上一步無(wú)法處理消息,且目標(biāo)對(duì)象實(shí)現(xiàn)了-forwardingTargetForSelector:
,Runtime 這時(shí)就會(huì)調(diào)用這個(gè)方法,給你把這個(gè)消息轉(zhuǎn)發(fā)給其他對(duì)象的機(jī)會(huì)。 只要這個(gè)方法返回的不是nil和self,整個(gè)消息發(fā)送的過(guò)程就會(huì)被重啟,當(dāng)然發(fā)送的對(duì)象會(huì)變成你返回的那個(gè)對(duì)象。否則,就會(huì)繼續(xù)Normal Fowarding。 這里叫Fast,只是為了區(qū)別下一步的轉(zhuǎn)發(fā)機(jī)制。因?yàn)檫@一步不會(huì)創(chuàng)建任何新的對(duì)象,但下一步轉(zhuǎn)發(fā)會(huì)創(chuàng)建一個(gè)NSInvocation對(duì)象,所以相對(duì)更快點(diǎn)。
@interface SUTRuntimeMethodHelper : NSObject
- (void)method2;
@end
@implementation SUTRuntimeMethodHelper
- (void)method2 {
NSLog(@"%@, %p", self, _cmd);
}
@end
#pragma mark -
@interface SUTRuntimeMethod () {
SUTRuntimeMethodHelper *_helper;
}
@end
@implementation SUTRuntimeMethod
+ (instancetype)object {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (self != nil) {
_helper = [[SUTRuntimeMethodHelper alloc] init];
}
return self;
}
- (void)test {
[self performSelector:@selector(method2)];
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
NSLog(@"forwardingTargetForSelector");
NSString *selectorString = NSStringFromSelector(aSelector);
// 將消息轉(zhuǎn)發(fā)給_helper來(lái)處理
if ([selectorString isEqualToString:@"method2"]) {
return _helper;
}
return [super forwardingTargetForSelector:aSelector];
}
@end
This method gives an object a chance to redirect an unknown message sent to it before the much more expensive forwardInvocation: machinery takes over. This is useful when you simply want to redirect messages to another object and can be an order of magnitude faster than regular forwarding. It is not useful where the goal of the forwarding is to capture the NSInvocation, or manipulate the arguments or return value during the forwarding.
Normal forwarding
如果在上一步還不能處理未知消息,則唯一能做的就是啟用完整的消息轉(zhuǎn)發(fā)機(jī)制了。
這一步是Runtime最后一次給你挽救的機(jī)會(huì)。首先它會(huì)調(diào)用-methodSignatureForSelector:
方法獲得NSMethodSignature
類(lèi)型的函數(shù)簽名,如果返回了一個(gè)函數(shù)簽名,Runtime就會(huì)創(chuàng)建一個(gè)NSInvocation
對(duì)象并調(diào)用-forwardInvocation:
方法。如果-methodSignatureForSelector:
返回nil,Runtime則會(huì)發(fā)出-doesNotRecognizeSelector:
消息,程序這時(shí)也就掛掉了。
NSObject的forwardInvocation:方法實(shí)現(xiàn)只是簡(jiǎn)單調(diào)用了doesNotRecognizeSelector:方法,它不會(huì)轉(zhuǎn)發(fā)任何消息。
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
if (!signature) {
if ([SUTRuntimeMethodHelper instancesRespondToSelector:aSelector]) {
signature = [SUTRuntimeMethodHelper instanceMethodSignatureForSelector:aSelector];
}
}
return signature;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
if ([SUTRuntimeMethodHelper instancesRespondToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:_helper];
}else{
[super forwardInvocation:anInvocation];
}
}
Category
Method Swizzling
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
//當(dāng)類(lèi)中沒(méi)有originalSelector的實(shí)現(xiàn)的時(shí)候才會(huì)添加成功,否則添加失敗
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
@end
為什么上面不直接使用method_exchangeImplementations,而是先使用class_addMethod呢?因?yàn)橹苯咏粨Q IMP 是很危險(xiǎn)的。如果這個(gè)類(lèi)中沒(méi)有實(shí)現(xiàn)這個(gè)方法,但是父類(lèi)實(shí)現(xiàn)了,那么class_getInstanceMethod() 返回的是某個(gè)父類(lèi)的 Method 對(duì)象,這樣 method_exchangeImplementations() 就把父類(lèi)的原始實(shí)現(xiàn)(IMP)跟這個(gè)類(lèi)的 Swizzle 實(shí)現(xiàn)交換了。這樣其他父類(lèi)及其其他子類(lèi)的方法調(diào)用就會(huì)出問(wèn)題,最嚴(yán)重的就是 Crash。
有時(shí)為了避免方法命名沖突和參數(shù) _cmd 被篡改,也會(huì)使用下面這種『靜態(tài)方法版本』的 Method Swizzle。CaptainHook 中的宏定義也是采用這種方式,比較推薦:
def IMP *IMPPointer;
static void MethodSwizzle(id self, SEL _cmd, id arg1);
static void (*MethodOriginal)(id self, SEL _cmd, id arg1);
static void MethodSwizzle(id self, SEL _cmd, id arg1) {
// do custom work
MethodOriginal(self, _cmd, arg1);
}
BOOL class_swizzleMethodAndStore(Class class, SEL original, IMP replacement, IMPPointer store) {
IMP imp = NULL;
Method method = class_getInstanceMethod(class, original);
if (method) {
const char *type = method_getTypeEncoding(method);
imp = class_replaceMethod(class, original, replacement, type);
if (!imp) {
imp = method_getImplementation(method);
}
}
if (imp && store) { *store = imp; }
return (imp != NULL);
}
+ (BOOL)swizzle:(SEL)original with:(IMP)replacement store:(IMPPointer)store {
return class_swizzleMethodAndStore(self, original, replacement, store);
}
+ (void)load {
[self swizzle:@selector(originalMethod:) with:(IMP)MethodSwizzle store:(IMP *)&MethodOriginal];
}
store傳入了MethodOriginal的地址,通過(guò)*store = imp;
把之前的orginal映射的IMP賦值給了MethodOriginal,之后就可以通過(guò) MethodOriginal(self, _cmd, arg1);
調(diào)用之前的方法了。
常用方法
class_getInstanceMethod(Class _Nullable __unsafe_unretained cls, SEL _Nonnull name)
:當(dāng)類(lèi)和其父類(lèi)都沒(méi)有selector映射的方法是現(xiàn)時(shí),會(huì)返回null。
class_addMethod()
:若果類(lèi)里沒(méi)有要添加的方法(不管父類(lèi)有沒(méi)有),則會(huì)添加一個(gè)新的方法(如果父類(lèi)也有這個(gè)方法,則相當(dāng)于重寫(xiě)了父類(lèi)的方法),返回值為YES;如果類(lèi)里已經(jīng)有了要添加的方法,則不會(huì)添加,返回值為NO。