Runtime源碼 protocol(協議)

1、概述

協議定義了一個綱領性的接口,全部類均可以選擇實現。它主要是用來定義一套對象之間的通訊規則。protocol也是咱們設計時經常使用的一個東西,相對於直接繼承的方式,protocol則偏向於組合模式。他使得兩個絕不相關的類可以相互通訊,從而實現特定的目標。由於OC是單繼承的,因爲不支持多繼承,因此不少時候都是用Protocol和Category來代替實現"多繼承"。html

2、底層實現

在objc4-723中protocol的定義以下:bash

struct protocol_t : objc_object {
	const char *mangledName;
    struct protocol_list_t *protocols;
    method_list_t *instanceMethods;
    method_list_t *classMethods;
    method_list_t *optionalInstanceMethods;
    method_list_t *optionalClassMethods;
    property_list_t *instanceProperties;
    uint32_t size;   // sizeof(protocol_t)
    uint32_t flags;
    // Fields below this point are not always present on disk.
    const char **_extendedMethodTypes;
    const char *_demangledName;
    property_list_t *_classProperties;

    const char *demangledName();
    ...
};

複製代碼

咱們能夠看到protocol繼承自objc_object,裏面的字段基本算是清晰,主要結構以下:app

  • mangledName 和 _demangledName
    這是來源於C++的name mangling(命名重整)技術,在C++裏面用來區別重載是的函數。函數

  • protocols
    它是protocol_list_t類型的指針,保存了這個協議所遵照的協議;ui

  • instanceMethods
    實例方法列表this

  • calssMethods
    類方法列表atom

  • optionalInstanceMethods
    可選擇實現的實例方法,在聲明時用@optional關鍵字修飾的實例方法spa

  • optionalClassMethods
    可選擇實現的類方法,在聲明時用@optional關鍵字修飾的類方法設計

  • instanceProperties
    實例屬性指針

  • _classProperties
    類屬性,比較少見

    @property (nonatomic, strong) NSString *name;//經過實例調用
    @property (class, nonatomic, strong) NSString *className;//經過類名調用
    複製代碼

3、 經常使用方法

  • protocol_copyPropertyList
    runtime提供了兩個方法:
objc_property_t *
protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
{
    return protocol_copyPropertyList2(proto, outCount, 
                                      YES/*required*/, YES/*instance*/);
}


objc_property_t *
protocol_copyPropertyList2(Protocol *proto, unsigned int *outCount, 
                           BOOL isRequiredProperty, BOOL isInstanceProperty)
{
    if (!proto  ||  !isRequiredProperty) {
        // Optional properties are not currently supported.
        if (outCount) *outCount = 0;
        return nil;
    }

    rwlock_reader_t lock(runtimeLock);

    property_list_t *plist = isInstanceProperty
        ? newprotocol(proto)->instanceProperties
        : newprotocol(proto)->classProperties();
    return (objc_property_t *)copyPropertyList(plist, outCount);
}

複製代碼

// Optional properties are not currently supported.
這裏指明瞭可選屬性如今還不支持,這就是沒有可選屬性的緣由

  • conformsToProtocol()
+ (BOOL)conformsToProtocol:(Protocol *)protocol {
    if (!protocol) return NO;
    for (Class tcls = self; tcls; tcls = tcls->superclass) {
        if (class_conformsToProtocol(tcls, protocol)) return YES;
    }
    return NO;
}

- (BOOL)conformsToProtocol:(Protocol *)protocol {
    if (!protocol) return NO;
    for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
        if (class_conformsToProtocol(tcls, protocol)) return YES;
    }
    return NO;
}
複製代碼

兩個方法都是遍歷類的繼承集體,調用class_conformsToProtocol方法,其實現以下:

BOOL class_conformsToProtocol(Class cls, Protocol *proto_gen)
{
    protocol_t *proto = newprotocol(proto_gen);
    
    if (!cls) return NO;
    if (!proto_gen) return NO;

    rwlock_reader_t lock(runtimeLock);

    assert(cls->isRealized());

    for (const auto& proto_ref : cls->data()->protocols) {
        protocol_t *p = remapProtocol(proto_ref);
        if (p == proto || protocol_conformsToProtocol_nolock(p, proto)) {
            return YES;
        }
    }

    return NO;
}
複製代碼

把class的protocols取出來,並與傳入的protocol作比較,若是地址相同直接返回,或者協議"繼承"的層級中知足條件:

/***********************************************************************
* protocol_conformsToProtocol_nolock
* Returns YES if self conforms to other.
* Locking: runtimeLock must be held by the caller.
**********************************************************************/
static bool 
protocol_conformsToProtocol_nolock(protocol_t *self, protocol_t *other)
{
    runtimeLock.assertLocked();

    if (!self  ||  !other) {
        return NO;
    }

    // protocols need not be fixed up

    if (0 == strcmp(self->mangledName, other->mangledName)) {
        return YES;
    }

    if (self->protocols) {
        uintptr_t i;
        for (i = 0; i < self->protocols->count; i++) {
            protocol_t *proto = remapProtocol(self->protocols->list[i]);
            if (0 == strcmp(other->mangledName, proto->mangledName)) {
                return YES;
            }
            if (protocol_conformsToProtocol_nolock(proto, other)) {
                return YES;
            }
        }
    }

    return NO;
}
複製代碼

遞歸處理,對比協議的mangledName,有相同的就返回YES。

參考:
協議protocol
Protocol

相關文章
相關標籤/搜索