Runtime 學習:消息傳遞

Objective-C 擴展了 C 語言,並加入了面向對象特性和消息傳遞機制。而這個擴展的核心就是 Runtime 庫。它是 Objective-C 面向對象和動態機制的基石。html

基於我對 Runtime 的理解,我認爲它的核心知識基本都圍繞兩個中心:數組

  • 消息傳遞
  • 類的動態配置

Runtime 的知識點比較多,計劃用三篇文章來記錄下本身的學習過程:緩存

下面就根據這兩個中心咱們慢慢來學習 Runtime。首先咱們須要對類的本質進行了解。bash

預備知識

類對象(objc_class)

Objective-C 類是由 Class 類型來表示的,它其實是一個指向 objc_class 結構體的指針。數據結構

typedef struct objc_class *Class;

複製代碼

查看 objc/runtime.hobjc_class 結構體的定義以下:app

//runtime.h
struct objc_class {
	// isa指針,指向元類(metaClass)
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
	// 父類
    Class _Nullable super_class                              OBJC2_UNAVAILABLE;
    // 類名
    const char * _Nonnull name                               OBJC2_UNAVAILABLE;
    // 類的版本信息,默認爲0
    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 的定義中,有幾個咱們比較感興趣的對象:ide

isa 在 Objective-C 中,類自身也是一個對象,它的 isa 指針指向其 metaClass(元類)。函數

super_class 指向該類的父類,若是該類已是最頂層的根類(如 NSObject),則super_class 爲 NULL。學習

objc_method_list 該類中的全部實例方法鏈表。ui

objc_cache 實例調用過的方法緩存。

類緩存(objc_cache)

struct objc_cache {
    unsigned int mask /* total = mask + 1 */                 OBJC2_UNAVAILABLE;
    unsigned int occupied                                    OBJC2_UNAVAILABLE;
    Method _Nullable buckets[1]                              OBJC2_UNAVAILABLE;
};
複製代碼

它包含了下面三個變量:

  • mask: 指定分配的緩存 bucket 的總數。,因此緩存的 size(total)是 mask+1。

  • occupied: 指定實際佔用的緩存bucket的總數。

  • buckets: 指向 Method 數據結構指針的數組。

爲了加速消息分發, 系統會對方法和對應的地址進行緩存,就放在 objc_cache 中,因此在實際運行中,大部分經常使用的方法都是會被緩存起來的。

Method(objc_method)

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_list 是一個鏈表。

struct objc_method {
     SEL _Nonnull method_name                                 OBJC2_UNAVAILABLE;
     char * _Nullable method_types                            OBJC2_UNAVAILABLE;
     IMP _Nonnull method_imp                                  OBJC2_UNAVAILABLE;
 }
複製代碼
  • method_name 方法名
  • method_types 方法類型
  • method_imp 方法實現

關於方法類型,能夠查看官方文檔中的定義。

SEL(objc_selector)

方法選擇器。是表示一個方法的 selector 的指針。

/// An opaque type that represents a method selector.
typedef struct objc_selector *SEL;
複製代碼

方法的 selector 用於表示運行時方法的名字。Objective-C 在編譯時,會依據每個方法的名字、參數序列,生成一個惟一的整型標識(Int類型的地址),這個標識就是SEL。

兩個類之間,無論它們是父類與子類的關係,仍是之間沒有這種關係,只要方法名相同,那麼方法的SEL就是同樣的。每個方法都對應着一個 SEL。因此在 Objective-C 同一個類(及類的繼承體系)中,不能存在兩個同名的方法,即便參數類型不一樣也不行。

舉例:

- (void)addNum:(int)num;
- (void)addNum:(CGFloat)num;
複製代碼

這樣的定義會致使編譯錯誤,由於這樣的 SEL 是相同的,並不能區分。須要改爲下方的:

- (void)addIntNum:(int)num;
- (void)addCGFloadNum:(CGFloat)num;
複製代碼

固然,不一樣的類能夠擁有相同的 selector,這個沒有問題。不一樣類的實例對象執行相同的 selector 時,會在各自的方法列表中去根據 selector 去尋找本身對應的 IMP。

IMP

是一個函數指針,指向方法的實現。

/// A pointer to the function of a method implementation. 
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ ); 
#else
typedef id _Nullable (*IMP)(id _Nonnull, SEL _Nonnull, ...); 
#endif
複製代碼

第一個參數是指向 self 的指針(若是是實例方法,則是類實例的內存地址;若是是類方法,則是指向元類的指針),第二個參數是方法選擇器(selector),接下來是方法的實際參數列表。

上面介紹的 SEL 就是爲了查找方法的最終實現 IMP 的。因爲每一個方法對應惟一的 SEL,所以咱們能夠經過 SEL 方便快速準確地得到它所對應的 IMP。

實例(objc_object)

查看 objc/objc.hobjc_object 結構體的定義以下:

/// Represents an instance of a class.
struct objc_object {
    Class _Nonnull isa  OBJC_ISA_AVAILABILITY;
};
/// A pointer to an instance of a class.
typedef struct objc_object *id;
複製代碼

能夠看到,實例的定義中只有一個 isa 指針字段,它是指向本類的指針。根據 objc_class 定義能夠得知關於這個對象的全部基本信息都存儲在 objc_class 中。因此,objc_object 須要的就是一個指向其類對象的 isa 指針。這樣當咱們向一個 Objective-C 對象發送消息時,Runtime 會根據實例對象的 isa 指針找到這個實例對象所屬的類。

元類(Meta Class)

當咱們調用對象方法時(即給實例對象發送消息),是根據 isa 指針尋找到這個對象(objc_object)的類(objc_class),再尋找到對應的方法實現。對應的咱們調用類方法時(即給類對象發送消息),也須要根據 isa 指針尋找到一個包含這些類方法的一個 objc_class 結構體。這就引出了 meta-class 的概念,元類中保存了建立類對象以及類方法所需的全部信息。

簡單來講——元類是類對象的類。

元類,就像以前的類同樣,它也是一個對象。你也能夠調用它的方法。天然的,這就意味着他必須也有一個類。

任何 NSObject 繼承體系下的 meta-class 都使用 NSObject 的 meta-class 做爲本身的所屬類,而基類的 meta-class 的 isa 指針是指向它本身。

NSString爲例

方法傳遞

這裏咱們從實際的代碼調用中來學習方法傳遞的所有過程。

簡單的 Objective-C 代碼調用:

[test testMethod];
複製代碼

利用 clang -rewrite-objc filename 代碼轉換爲:

((void (*)(id, SEL))(void *)objc_msgSend)((id)test, sel_registerName("testMethod"));
複製代碼

能夠看出

[test testMethod];
複製代碼

實質上就是

objc_msgSend((id)test, sel_registerName("testMethod"))
複製代碼

而後,咱們能夠在源碼中查看 objc_msgSend 的執行步驟。因爲源碼是用匯編寫的,這裏就不貼出來了(主要是本身也看不懂彙編)。若是有興趣的話,能夠去下載官方源碼在 objc_msg-xxx 文件中查看。

雖然,源碼是用匯編寫的,可是從註釋中咱們基本能夠看出具體的執行步驟。

  1. 進入消息發送階段,判斷消息接受者是否爲 nil。
  2. 利用 isa 指針找到本身的類對象。
  3. 在類對象的 objc_cache(方法緩存)中查找是否有方法,有則直接取出 Method(方法)中 IMP(實現)。無則繼續。
  4. 在類對象的 objc_method_list 中查找方法。有則直接取出,無則繼續。
  5. 找到類對象的 super_class ,繼續在其父類中重複上面兩個步驟進行查找。
  6. 若一直往上都沒有找到方法的實現,那麼消息發送階段結束,接着會進入動態解析階段,在這個階段,若解析到方法,則結束。不然繼續。
  7. 最後會進入消息轉發階段,在這裏能夠指定別的類爲本身實現這個方法。
  8. 若上方步驟都沒有找到方法的實現,則會報方法找不到的錯誤,沒法識別消息,unrecognzied selector sent to instance。

消息傳遞流程

上面8個步驟,能夠看到消息傳遞的過程分爲了如下三個階段:

  • 消息發送階段
  • 動態解析階段
  • 消息轉發階段

消息發送階段

從上方的分析能夠獲得: 方法查找的核心函數就是 _class_lookupMethodAndLoadCache3 函數,接下來重點分析 _class_lookupMethodAndLoadCache3 函數內的源碼。

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
複製代碼

lookUpImpOrForward 函數

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
	// initialize = YES , cache = NO , resolver = YES
    IMP imp = nil;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

	// 緩存查找, 由於cache傳入的爲NO, 這裏不會進行緩存查找, 由於在彙編語言中CacheLookup已經查找過
    // Optimistic cache lookup
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    // runtimeLock is held during isRealized and isInitialized checking
    // to prevent races against concurrent realization.

    // runtimeLock is held during method search to make
    // method-lookup + cache-fill atomic with respect to method addition.
    // Otherwise, a category could be added but ignored indefinitely because
    // the cache was re-filled with the old value after the cache flush on
    // behalf of the category.

    runtimeLock.lock();
    checkIsKnownClass(cls);

    if (!cls->isRealized()) {
        realizeClass(cls);
    }

    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // If sel == initialize, _class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172 } retry: runtimeLock.assertLocked(); // Try this class's cache.

	// 防止動態添加方法,緩存會變化,再次查找緩存。
    imp = cache_getImp(cls, sel);
    
    // 若是查找到imp, 直接調用done, 返回方法地址
    if (imp) goto done;

	// 查找方法列表, 傳入類對象和方法名
    // Try this class's method lists. { // 根據sel去類對象裏面查找方法 Method meth = getMethodNoSuper_nolock(cls, sel); if (meth) { // 若是方法存在,則緩存方法 log_and_fill_cache(cls, meth->imp, sel, inst, cls); // 方法緩存以後, 取出imp, 調用done返回imp imp = meth->imp; goto done; } } // 若是類方法列表中沒有找到, 則去父類的緩存中或方法列表中查找方法 // Try superclass caches and method lists. { unsigned attempts = unreasonableClassCount(); for (Class curClass = cls->superclass; curClass != nil; curClass = curClass->superclass) { // Halt if there is a cycle in the superclass chain. if (--attempts == 0) { _objc_fatal("Memory corruption in class list."); } // 查找父類的緩存 // Superclass cache. imp = cache_getImp(curClass, sel); if (imp) { if (imp != (IMP)_objc_msgForward_impcache) { // 在父類中找到方法, 在本類中緩存方法, 注意這裏傳入的是cls, 將方法緩存在本類緩存列表中, 而非父類中 // Found the method in a superclass. Cache it in this class. log_and_fill_cache(cls, imp, sel, inst, curClass); goto done; } else { // Found a forward:: entry in a superclass. // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            // 查找父類的方法列表
            // Superclass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
            		// 一樣拿到方法, 在本類進行緩存
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }
    
    // ---------------- 消息發送階段完成 ---------------------
    
    // ---------------- 進入動態解析階段 ---------------------
	
	
	 // 上述列表中都沒有找到方法實現, 則嘗試解析方法
    // No implementation found. Try method resolver once.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }
	
	 // ---------------- 動態解析階段完成 ---------------------

    // ---------------- 進入消息轉發階段 ---------------------
	
    // No implementation found, and method resolver didn't help. // Use forwarding. imp = (IMP)_objc_msgForward_impcache; cache_fill(cls, sel, imp, inst); done: runtimeLock.unlock(); return imp; } 複製代碼

根據上方源碼的解析,獲得消息發送階段的流程如圖:

消息發送流程

動態解析階段

當消息發送階段沒有找到方法實現的時候,就會進入動態方法解析階段。咱們來看一下動態解析階段源碼。

if (resolver  &&  !triedResolver) {
    runtimeLock.unlock();
    _class_resolveMethod(cls, sel, inst);
    runtimeLock.lock();
    // Don't cache the result; we don't hold the lock so it may have 
    // changed already. Re-do the search from scratch instead.
    triedResolver = YES;
    goto retry;
}

void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}
複製代碼

上述代碼中能夠發現,動態解析方法以後,會將triedResolver = YES;那麼下次就不會在進行動態解析階段了,以後會從新執行retry,會從新對方法查找一遍。也就是說不管咱們是否實現動態解析方法,不管動態解析方法是否成功,retry以後都不會在進行動態的解析方法了。

  • 對象方法

動態解析對象方法時,會調用 _class_resolveInstanceMethod(cls, sel, inst) 方法。對應的 Objective-C 的方法是 +(BOOL)resolveInstanceMethod:(SEL)sel。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //執行foo函數
    [self performSelector:@selector(foo:)];
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(foo:)) {//若是是執行foo函數,就動態解析,指定新的IMP
        class_addMethod([self class], sel, (IMP)fooMethod, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

void fooMethod(id obj, SEL _cmd) {
    NSLog(@"Doing foo");//新的foo函數
}
複製代碼
  • 類方法

動態解析類方法時,會調用 _class_resolveClassMethod(cls, sel, inst) 方法,對應的 Objective-C 的方法是 +(BOOL)resolveClassMethod:(SEL)sel。

@implementation Person

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //執行foo函數
    [Person foo];
}

+ (BOOL)resolveClassMethod:(SEL)sel
{
    if (sel == @selector(foo)) {
        // 第一個參數是object_getClass(self),傳入元類對象。
        class_addMethod(object_getClass(self), sel, (IMP)fooMethod, "v16@0:8");
        return YES;
    }
    return [super resolveClassMethod:sel];
}

void fooMethod(id obj, SEL _cmd) {
    NSLog(@"Doing foo");//新的foo函數
}
複製代碼

上面的代碼中,當動態解析方法時,咱們動態的添加了方法的實現,這裏引入了一個函數 class_addMethod,這個函數就是動態配置類時的關鍵函數之一。

咱們看一下這個函數的聲明:

BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types);
複製代碼

cls: 給哪一個類添加方法。

name: 須要添加的方法名。 Objective-C 中能夠直接使用 @selector(methodName) 獲得方法名, Swift 中使用 #Selector(methodName)。

imp: 方法的實現,函數入口,函數名可與方法名不一樣(建議與方法名相同)。函數必須至少兩個參數—— self 和 _cmd。

types: 參數以及返回值類型的字符串,須要用特定符號,參考官方文檔Type encodings

咱們從整個動態解析的過程能夠看到,不管咱們是否實現了動態解析的方法,系統內部都會執行 retry 對方法再次進行查找。那麼若是咱們實現了動態解析方法,此時就會順利查找到方法,進而返回 imp 對方法進行調用。若是咱們沒有實現動態解析方法。就會進行消息轉發。

動態解析流程

消息轉發階段

當本類沒有實現方法,而且沒有動態解析方法,Runtime 這時就會調用 forwardingTargetForSelector 函數,進行消息轉發,咱們能夠實現forwardingTargetForSelector 函數,在其內部將消息轉發給能夠實現此方法的對象。

實現一個完整轉發的例子以下:

#import "Car.h"
@implementation Car
- (void) driving
{
    NSLog(@"car driving");
}
@end

--------------

#import "Person.h"
#import <objc/runtime.h>
#import "Car.h"
@implementation Person

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return YES;//返回YES,進入下一步轉發
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    // 返回可以處理消息的對象
    if (aSelector == @selector(driving)) {
        return [[Car alloc] init];
    }
    return [super forwardingTargetForSelector:aSelector];
}
@end

--------------

#import<Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *person = [[Person alloc] init];
        [person driving];
    }
    return 0;
}

// 打印內容
// 消息轉發 car driving  
複製代碼

若是 forwardingTargetForSelector 函數返回爲 nil 或者沒有實現的話,就會調用methodSignatureForSelector方法,用來返回一個方法簽名,這也是咱們正確跳轉方法的最後機會。

若是 methodSignatureForSelector 方法返回正確的方法簽名就會調用 forwardInvocation 方法,forwardInvocation 方法內提供一個 NSInvocation 類型的參數,NSInvocation 封裝了一個方法的調用,包括方法的調用者,方法名,以及方法的參數。在 forwardInvocation 函數內修改方法調用對象便可。

若是 methodSignatureForSelector 返回的爲 nil,就會來到 doseNotRecognizeSelector: 方法內部,程序 crash 提示沒法識別選擇器 unrecognized selector sent to instance。

代碼驗證:

#import "Car.h"
@implementation Car
- (void) driving
{
    NSLog(@"car driving");
}
@end

--------------

#import<Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *person = [[Person alloc] init];
        [person driving];
    }
    return 0;
}

--------------

#import "Person.h"
#import <objc/runtime.h>
#import "Car.h"
@implementation Person

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return YES;//返回YES,進入下一步轉發
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    // 返回可以處理消息的對象
    if (aSelector == @selector(driving)) {
        // 返回nil則會調用methodSignatureForSelector方法
        return nil; 
        // return [[Car alloc] init];
    }
    return [super forwardingTargetForSelector:aSelector];
}

// 方法簽名:返回值類型、參數類型
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(driving)) {
       // 經過調用Car的methodSignatureForSelector方法獲得方法簽名,這種方式須要car對象有aSelector方法
        return [[[Car alloc] init] methodSignatureForSelector: aSelector];

    }
    return [super methodSignatureForSelector:aSelector];
}

/*
* NSInvocation 封裝了一個方法調用,包括:方法調用者,方法,方法的參數
*    anInvocation.target 方法調用者
*    anInvocation.selector 方法名
*    [anInvocation getArgument: NULL atIndex: 0]; 得到參數
*/    
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
//   anInvocation中封裝了methodSignatureForSelector函數中返回的方法。
//   此時anInvocation.target 仍是person對象,咱們須要修改target爲能夠執行方法的方法調用者。
//   anInvocation.target = [[Car alloc] init];
//   [anInvocation invoke];
    [anInvocation invokeWithTarget: [[Car alloc] init]];
}
@end

// 打印內容
// 消息轉發 car driving
複製代碼

類方法消息轉發同對象方法同樣,一樣須要通過消息發送,動態方法解析以後纔會進行消息轉發機制。須要注意的是類方法的接受者爲類對象。其餘同對象方法消息轉發模式相同。

當類對象進行消息轉發時,對調用相應的 + 號的 forwardingTargetForSelector、methodSignatureForSelector、forwardInvocation 方法。

消息轉發流程
相關文章
相關標籤/搜索