前言
objective-c 是一門動態語言,它將很多靜態語言在編譯和鏈接時期做的事情,放到了運行時來處理。之所以能具備這種特性,離不開 runtime 這個庫。runtime 很好的解決了如何在運行時期找到調用方法這樣的問題。下面話不多說了,來一起學習學習吧。
在 objective-c 中,方法調用稱為向對象發送消息:
1
2
3
4
5
6
7
8
9
10
11
12
|
// myclass 類 @interface myclass: nsobject - ( void )printlog; @end @implementation myclass - ( void )printlog { nslog(@ "print log !" ); } @end myclass *myclass = [[myclass alloc] init]; [myclass printlog]; // 輸出: print log ! |
上面代碼中的 [myclass printlog] 也可以這么寫:
1
|
(( void (*)(id, sel))( void *) objc_msgsend)(myclass, @selector(printlog)); |
[myclass printlog] 經過編譯后就是調用 objc_msgsend 方法。
我們看看這個方法的文檔定義:
1
|
id objc_msgsend(id self, sel op, ...); |
self:消息的接收者 op: 消息的方法名,c 字符串 ... :參數列表
runtime 是如何找到實例方法的具體實現的?
基礎概念
講之前,我們需要先明白一些基礎概念:objective-c 是一門面向對象的語言,對象又分為實例對象、類對象、元類對象以及根元類對象。它們是通過一個叫 isa 的指針來關聯起來,具體關系如下圖:
以我們上文的代碼為例:
1
|
myclass *myclass = [[myclass alloc] init]; |
整理下相互間的關系:
- myclass 是實例對象
- myclass 是類對象
- myclass 的元類就是 nsobject 的元類
- nsobject 就是 root class (class)
- nsobject 的 superclass 為 nil
- nsobject 的元類就是它自己
- nsobject 的 superclass 就是 nsobject
對應上圖中的位置關系如下:
接著,我們用代碼來驗證下上文的關系:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
myclass *myclass = [[myclass alloc] init]; class class = [myclass class ]; class metaclass = object_getclass( class ); class metaofmetaclass = object_getclass(metaclass); class rootmetaclass = object_getclass(metaofmetaclass); class superclass = class_getsuperclass( class ); class superofsuperclass = class_getsuperclass(superclass); class superofmetaofsuperclass = class_getsuperclass(object_getclass(superclass)); nslog(@ "myclass 實例對象是:%p" ,myclass); nslog(@ "myclass 類對象是:%p" , class ); nslog(@ "myclass 元類對象是:%p" ,metaclass); nslog(@ "myclass 元類對象的元類對象是:%p" ,metaofmetaclass); nslog(@ "myclass 根元類對象是:%p" ,rootmetaclass); nslog(@ "myclass 父類是:%@" ,class_getsuperclass( class )); nslog(@ "myclass 父類的父類是:%@" ,superofsuperclass); nslog(@ "myclass 父類的元類的父類是:%@" ,superofmetaofsuperclass); nslog(@ "nsobject 元類對象是:%p" ,object_getclass([nsobject class ])); nslog(@ "nsobject 父類是:%@" ,[[nsobject class ] superclass]); nslog(@ "nsobject 元類對象的父類是:%@" ,[object_getclass([nsobject class ]) superclass]); //輸出: myclass 實例對象是:0x60c00000b8d0 myclass 類對象是:0x109ae3fd0 myclass 元類對象是:****0x109ae3fa8 myclass 元類對象的元類對象是:****0x10ab02e58** myclass 根元類對象是:0x10ab02e58 myclass 父類是:nsobject myclass 父類的父類是:(null) myclass 父類的元類的父類是:nsobject nsobject 元類對象是:0x10ab02e58 nsobject 父類是:(null) nsobject 元類對象的父類是:nsobject |
可以發現,輸出結果是完全符合我們的結論的!
現在我們能知道各種對象之間的關系:
實例對象通過 isa 指針,找到類對象 class;類對象同樣通過 isa 指針,找到元類對象;元類對象也是通過 isa 指針,找到根元類對象;最后,根元類對象的 isa 指針,指向自己。可以發現 nsobject 是整個消息機制的核心,絕大數對象都繼承自它。
尋找流程
上文提到了,一個 objective-c 方法會被編譯成 objc_msgsend,這個函數有兩個默認參數,id 類型的 self, sel 類型的 op。我們先看看 id 的定義:
1
2
3
4
|
typedef struct objc_object *id; struct objc_object { class _nonnull isa objc_isa_availability; }; |
我們可以看到,在 objc_object 結構體中,只有一個指向 class 類型的 isa 指針。
我們再看看 class 的定義:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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; |
里面有很多參數,很顯眼的能看到這一行:
1
|
struct objc_method_list * _nullable * _nullable methodlists objc2_unavailable; |
看名字也容易理解,這個 methodlists 就是用來存放方法列表的。我們再看看 objc_method_list 這個結構體:
1
2
3
4
5
6
7
8
9
10
|
struct objc_method_list { struct objc_method_list * _nullable obsolete objc2_unavailable; int method_count objc2_unavailable; #ifdef __lp64__ int space objc2_unavailable; #endif /* variable length structure */ struct objc_method method_list[1] objc2_unavailable; } |
里面的 objc_method ,也就是我們熟悉的 method:
1
2
3
4
5
|
struct objc_method { sel _nonnull method_name objc2_unavailable; char * _nullable method_types objc2_unavailable; imp _nonnull method_imp objc2_unavailable; } |
method 里面保存了三個參數:
- 方法的名稱
- 方法的類型
- 方法的具體實現,由 imp 指針指向
經過層層挖掘,我們能明白實例對象調用方法的大致邏輯:
1
2
|
myclass *myclass = [[myclass alloc] init]; [myclass printlog]; |
-
先被編譯成
((void (*)(id, sel))(void *) objc_msgsend)(myclass, @selector(printlog));
- 沿著入參 myclass 的 isa 指針,找到 myclass 的類對象(class),也就是 myclass
- 接著在 myclass 的方法列表 methodlists 中,找到對應的 method
- 最后找到 method 中的 imp 指針,執行具體實現
類對象的類方法又是怎么找到并執行的?
由上文,我們已經知道,實例對象是通過 isa 指針,找到其類對象(class)中保存的方法列表中的具體實現的。
比如:
1
2
|
myclass *myclass = [[myclass alloc] init]; [myclass printlog]; |
可以理解為:printlog 方法就是保存在 myclass 中的。
那么如果是個類方法,又是保存在什么地方的呢?
我們回顧下 class 的定義:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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; |
可以發現到這一行:
1
|
class _nonnull isa objc_isa_availability; |
這里的 isa 同樣是指向一個 class 的指針。上文中,我們也知道了類對象的 isa 指針是指向元類對象的。那么不難得出:
類對象的類方法,是保存在元類對象中的!
類對象和元類對象都是 class 類型,僅僅服務的對象不同罷了。找到了元類對象,自然就找到了元類對象中的 methodlists,接下來就和實例對象的方法尋找調用一樣的流程了。
關于父類(superclass)
在 objective-c 中,子類調用一個方法,如果沒有子類沒有實現,父類實現了,會去調用父類的實現。上文中,找到 methodlists 后,尋找 method 的過程如下:
如何提高方法查找的效率?
上文中,我們大概知道,方法是通過 isa 指針,查找 class 中的 methodlists 的。如果子類沒實現對應的方法實現,還會沿著父類去查找。整個工程,可能有成萬上億個方法,是如何解決性能問題的呢?
例如:
1
2
3
4
|
for ( int i = 0; i < 100000; ++i) { myclass *myobject = myobjects[i]; [myobject methoda]; } |
這種高頻次的調用 methoda,如果每調用一次都需要遍歷,性能是非常差的。所以引入了 class cache 機制:
class cache 認為,當一個方法被調用,那么它之后被調用的可能性就越大。
查找方法時,會先從緩存中查找,找到直接返回 ;找不到,再去 class 的方法列表中找。
在上文中 class 的定義中,我們可以發現 cache:
1
|
struct objc_cache * _nonnull cache objc2_unavailable; |
說明了緩存是存在類中的,每個類都有一份方法緩存,而不是每個類的 object 都保存了一份。
消息轉發
如果方法列表(methodlists)沒找到對應的 selector 呢?
1
2
|
// viewcontroller.m 中 (未實現 mytestprint 方法) [self performselector:@selector(mytestprint:) withobject:@ ",你好 !" ]; |
系統會提供三次補救的機會。
第一次
1
2
|
+ ( bool )resolveinstancemethod:(sel)sel {} (實例方法) + ( bool )resolveclassmethod:(sel)sel {} (類方法) |
這兩個方法,一個針對實例方法;一個針對類方法。返回值都是 bool。
使用示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// viewcontroller.m 中 void mymethod(id self, sel _cmd,nsstring *nub) { nslog(@ "ifelseboyxx%@" ,nub); } + ( bool )resolveinstancemethod:(sel)sel { #pragma clang diagnostic push #pragma clang diagnostic ignored "-wundeclared-selector" if (sel == @selector(mytestprint:)) { #pragma clang diagnostic pop class_addmethod([self class ],sel,(imp)mymethod, "v@:@" ); return yes; } else { return [super resolveinstancemethod:sel]; } } |
我們只需要在 resolveinstancemethod: 方法中,利用 class_addmethod 方法,將未實現的 mytestprint: 綁定到 mymethod 上就能完成轉發,最后返回 yes。
第二次
1
|
- (id)forwardingtargetforselector:(sel)aselector {} |
這個方法要求返回一個 id。使用場景一般是將 a 類的某個方法,轉發到 b 類的實現中去。
使用示例:
想轉發到 person 類中的 -mytestprint: 方法中:
1
2
3
4
5
6
7
|
@interface person : nsobject @end @implementation person - ( void )mytestprint:(nsstring *)str { nslog(@ "ifelseboyxx%@" ,str); } @end |
1
2
3
4
5
6
7
8
9
10
11
|
// viewcontroller.m 中 - (id)forwardingtargetforselector:(sel)aselector { #pragma clang diagnostic push #pragma clang diagnostic ignored "-wundeclared-selector" if (aselector == @selector(mytestprint:)) { #pragma clang diagnostic pop return [person new ]; } else { return [super forwardingtargetforselector:aselector]; } } |
第三次
1
2
|
- (nsmethodsignature *)methodsignatureforselector:(sel)aselector {} - ( void )forwardinvocation:(nsinvocation *)aninvocation {} |
第一個要求返回一個方法簽名,第二個方法轉發具體的實現。二者相互依賴,只有返回了正確的方法簽名,才會執行第二個方法。
這次的轉發作用和第二次的比較類似,都是將 a 類的某個方法,轉發到 b 類的實現中去。不同的是,第三次的轉發相對于第二次更加靈活,forwardingtargetforselector: 只能固定的轉發到一個對象;forwardinvocation: 可以讓我們轉發到多個對象中去。
使用實例:
想轉發到 person 類以及 animal 類中的 -mytestprint: 方法中:
1
2
3
4
5
6
7
|
@interface person : nsobject @end @implementation person - ( void )mytestprint:(nsstring *)str { nslog(@ "ifelseboyxx%@" ,str); } @end |
1
2
3
4
5
6
7
|
@interface animal : nsobject @end @implementation animal - ( void )mytestprint:(nsstring *)str { nslog(@ "tiger%@" ,str); } @end |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// viewcontroller.m 中 - (nsmethodsignature *)methodsignatureforselector:(sel)aselector { #pragma clang diagnostic push #pragma clang diagnostic ignored "-wundeclared-selector" if (aselector == @selector(mytestprint:)) { #pragma clang diagnostic pop return [nsmethodsignature signaturewithobjctypes: "v@:@" ]; } return [super methodsignatureforselector:aselector]; } - ( void )forwardinvocation:(nsinvocation *)aninvocation { person *person = [person new ]; animal *animal = [animal new ]; if ([person respondstoselector:aninvocation.selector]) { [aninvocation invokewithtarget:person]; } if ([animal respondstoselector:aninvocation.selector]) { [aninvocation invokewithtarget:animal]; } } |
?? 如果到了第三次機會,還沒找到對應的實現,就會 crash:
1
|
unrecognized selector sent to instance 0x7f9f817072b0 |
總結
到這里,我們大概能了解消息發送與轉發的過程了,附上流程圖:
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://juejin.im/post/5aa79411f265da237a4cb045