Objective-C runtime機制(4)——深入理解Category

在平日編程中或閱讀第三方代碼時,category可以說是無處不在。category也可以說是OC作為一門動態語言的一大特色。category為我們動態擴展類的功能提供了可能,或者我們也可以把一個龐大的類進行功能分解,按照category進行組織。

關于category的使用無需多言,今天我們來深入了解一下,category是如何在runtime中實現的。

category的數據結構

category對應到runtime中的結構體是struct category_t(位于objc-runtime-new.h):

struct category_t {
    const char *name;
    classref_t cls;
    struct method_list_t *instanceMethods;
    struct method_list_t *classMethods;
    struct protocol_list_t *protocols;
    struct property_list_t *instanceProperties;
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;

    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};

category_t的定義很簡單。從定義中看出,category 的可為:添加實例方法(instanceMethods),類方法(classMethods),協議(protocols)和實例屬性(instanceProperties),以及不可為:不能夠添加實例變量(關于實例屬性和實例變量的區別,我們將會在別的章節中探討)。

category的加載

知道了category的數據結構,我們來深入探究一下category是如何在runtime中實現的。

原理很簡單:runtime會分別將category 結構體中的instanceMethods, protocolsinstanceProperties添加到target class的實例方法列表,協議列表,屬性列表中,會將category結構體中的classMethods添加到target class所對應的元類的實例方法列表中。其本質就相當于runtime在運行時期,修改了target class的結構。

經過這一番修改,category中的方法,就變成了target class方法列表中的一部分,其調用方式也就一模一樣啦~

現在,就來看一下具體是怎么實現的。

首先,我們在Mach-O格式和runtime 介紹過在Mach-O文件中,category數據會被存放在__DATA段下的__objc_catlist section中。

當OC被dyld加載起來時,OC進入其入口點函數_objc_init

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
}

我們忽略一堆init方法,重點來看_dyld_objc_notify_register方法。該方法會向dyld注冊監聽Mach-O中OC相關section被加載入\載出內存的事件。

具體有三個事件:
_dyld_objc_notify_mapped(對應&map_images回調):當dyld已將OC images加載入內存時。
_dyld_objc_notify_init(對應load_images回調):當dyld將要初始化OC image時。OC調用類的+load方法,就是在這時進行的。
_dyld_objc_notify_unmapped(對應unmap_image回調):當dyld將OC images移除內存時。

而category寫入target class的方法列表,則是在_dyld_objc_notify_mapped,即將OC相關sections都加載到內存之后所發生的。

我們可以看到其對應回調為map_images方法。

map_images 最終會調用_read_images 方法來讀取OC相關sections,并以此來初始化OC內存環境。_read_images 的極簡實現版如下,可以看到,rumtime是如何根據Mach-O各個section的信息來初始化其自身的:

void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClasses)
{

    static bool doneOnce;
    TimeLogger ts(PrintImageTimes);
    
    runtimeLock.assertWriting();
    
    if (!doneOnce) {
        doneOnce = YES;
        
        ts.log("IMAGE TIMES: first time tasks");
    }
    
    
    // Discover classes. Fix up unresolved future classes. Mark bundle classes.
    
    for (EACH_HEADER) {
        
        classref_t *classlist = _getObjc2ClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = (Class)classlist[I];
            Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
        }
    }
    
    ts.log("IMAGE TIMES: discover classes");
    
    // Fix up remapped classes
    // Class list and nonlazy class list remain unremapped.
    // Class refs and super refs are remapped for message dispatching.

    for (EACH_HEADER) {
        Class *classrefs = _getObjc2ClassRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapClassRef(&classrefs[I]);
        }
        // fixme why doesn't test future1 catch the absence of this?
        classrefs = _getObjc2SuperRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapClassRef(&classrefs[I]);
        }
    }
   
    ts.log("IMAGE TIMES: remap classes");
    
    
    for (EACH_HEADER) {
        if (hi->isPreoptimized()) continue;
        
        bool isBundle = hi->isBundle();
        SEL *sels = _getObjc2SelectorRefs(hi, &count);
        UnfixedSelectors += count;
        for (i = 0; i < count; i++) {
            const char *name = sel_cname(sels[i]);
            sels[i] = sel_registerNameNoLock(name, isBundle);
        }
    }
    
    ts.log("IMAGE TIMES: fix up selector references");
    
    
    // Discover protocols. Fix up protocol refs.
    for (EACH_HEADER) {
        extern objc_class OBJC_CLASS_$_Protocol;
        Class cls = (Class)&OBJC_CLASS_$_Protocol;
        assert(cls);
        NXMapTable *protocol_map = protocols();
        bool isPreoptimized = hi->isPreoptimized();
        bool isBundle = hi->isBundle();
        
        protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
        for (i = 0; i < count; i++) {
            readProtocol(protolist[i], cls, protocol_map,
                         isPreoptimized, isBundle);
        }
    }
    
    ts.log("IMAGE TIMES: discover protocols");
    
    // Fix up @protocol references
    // Preoptimized images may have the right
    // answer already but we don't know for sure.
    for (EACH_HEADER) {
        protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
        for (i = 0; i < count; i++) {
            remapProtocolRef(&protolist[I]);
        }
    }
    
    ts.log("IMAGE TIMES: fix up @protocol references");
    
    // Realize non-lazy classes (for +load methods and static instances)
    for (EACH_HEADER) {
        classref_t *classlist =
        _getObjc2NonlazyClassList(hi, &count);
        for (i = 0; i < count; i++) {
            Class cls = remapClass(classlist[i]);
            if (!cls) continue;
            realizeClass(cls);
        }
    }
    
    ts.log("IMAGE TIMES: realize non-lazy classes");
    
    // Realize newly-resolved future classes, in case CF manipulates them
    if (resolvedFutureClasses) {
        for (i = 0; i < resolvedFutureClassCount; i++) {
            realizeClass(resolvedFutureClasses[I]);
            resolvedFutureClasses[i]->setInstancesRequireRawIsa(false/*inherited*/);
        }
        free(resolvedFutureClasses);
    }
    ts.log("IMAGE TIMES: realize future classes");
    
    // Discover categories.
    for (EACH_HEADER) {
        category_t **catlist =
        _getObjc2CategoryList(hi, &count);
        bool hasClassProperties = hi->info()->hasCategoryClassProperties();
        
        for (i = 0; i < count; i++) {
            category_t *cat = catlist[I];
            Class cls = remapClass(cat->cls);
            
            bool classExists = NO;
            if (cat->instanceMethods ||  cat->protocols
                ||  cat->instanceProperties)
            {
                addUnattachedCategoryForClass(cat, cls, hi);
            }
            
            if (cat->classMethods  ||  cat->protocols
                ||  (hasClassProperties && cat->_classProperties))
            {
                addUnattachedCategoryForClass(cat, cls->ISA(), hi);
            }
        }
    }
    
    ts.log("IMAGE TIMES: discover categories");
}

大致的邏輯是,runtime調用_getObjc2XXX格式的方法,依次來讀取對應的section內容,并根據其結果初始化其自身結構。

_getObjc2XXX 方法有如下幾種,可以看到他們都一一對應了Mach-O中相關的OC seciton。

//      function name                 content type     section name
GETSECT(_getObjc2SelectorRefs,        SEL,             "__objc_selrefs"); 
GETSECT(_getObjc2MessageRefs,         message_ref_t,   "__objc_msgrefs"); 
GETSECT(_getObjc2ClassRefs,           Class,           "__objc_classrefs");
GETSECT(_getObjc2SuperRefs,           Class,           "__objc_superrefs");
GETSECT(_getObjc2ClassList,           classref_t,      "__objc_classlist");
GETSECT(_getObjc2NonlazyClassList,    classref_t,      "__objc_nlclslist");
GETSECT(_getObjc2CategoryList,        category_t *,    "__objc_catlist");
GETSECT(_getObjc2NonlazyCategoryList, category_t *,    "__objc_nlcatlist");
GETSECT(_getObjc2ProtocolList,        protocol_t *,    "__objc_protolist");
GETSECT(_getObjc2ProtocolRefs,        protocol_t *,    "__objc_protorefs");
GETSECT(getLibobjcInitializers,       Initializer,     "__objc_init_func");

可以看到,我們使用的類,協議和category,都是在_read_images 方法中讀取出來的。
在讀取cateogry的方法 _getObjc2CategoryList(hi, &count)中,讀取的是Mach-O文件的 __objc_catlist 段。

我們重點關注和category相關的代碼:

    // Discover categories.
    for (EACH_HEADER) {
        category_t **catlist =
        _getObjc2CategoryList(hi, &count);
        bool hasClassProperties = hi->info()->hasCategoryClassProperties();
        
        for (i = 0; i < count; i++) {
            category_t *cat = catlist[I];
            Class cls = remapClass(cat->cls);
            
            bool classExists = NO;
            // 如果Category中有實例方法,協議,實例屬性,會改寫target class的結構
            if (cat->instanceMethods ||  cat->protocols
                ||  cat->instanceProperties)
            {
                addUnattachedCategoryForClass(cat, cls, hi);
                if (cls->isRealized()) {
                    remethodizeClass(cls);
                    classExists = YES;
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category -%s(%s) %s", 
                                 cls->nameForLogging(), cat->name, 
                                 classExists ? "on existing class" : "");
                }
            }
            // 如果category中有類方法,協議,或類屬性(目前OC版本不支持類屬性), 會改寫target class的元類結構
            if (cat->classMethods  ||  cat->protocols
                ||  (hasClassProperties && cat->_classProperties))
            {
                addUnattachedCategoryForClass(cat, cls->ISA(), hi);
                if (cls->ISA()->isRealized()) {
                    remethodizeClass(cls->ISA());
                }
                if (PrintConnecting) {
                    _objc_inform("CLASS: found category +%s(%s)", 
                                 cls->nameForLogging(), cat->name);
                }
            }
        }
    }
    
    ts.log("IMAGE TIMES: discover categories");

discover categories的邏輯如下:

  1. 先調用_getObjc2CategoryList讀取__objc_catlist seciton下所記錄的所有category。并存放到category_t *數組中。
  2. 依次讀取數組中的category_t * cat
  3. 對每一個cat,先調用remapClass(cat->cls),并返回一個objc_class *對象cls。這一步的目的在于找到到category對應的類對象cls
  4. 找到category對應的類對象cls后,就開始進行對cls的修改操作了。首先,如果category中有實例方法,協議,和實例屬性之一的話,則直接對cls進行操作。如果category中包含了類方法,協議,類屬性(不支持)之一的話,還要對cls所對應的元類(cls->ISA())進行操作。
  5. 不管是對cls還是cls的元類進行操作,都是調用的方法addUnattachedCategoryForClass。但這個方法并不是category實現的關鍵,其內部邏輯只是將class和其對應的category做了一個映射。這樣,以class為key,就可以取到所其對應的所有的category。
  6. 做好class和category的映射后,會調用remethodizeClass方法來修改class的method list結構,這才是runtime實現category的關鍵所在。

remethodizeClass

既然remethodizeClass是category的實現核心,那么我們就單獨一節,細看一下該方法的實現:


/***********************************************************************
* remethodizeClass
* Attach outstanding categories to an existing class.
* Fixes up cls's method list, protocol list, and property list.
* Updates method caches for cls and its subclasses.
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static void remethodizeClass(Class cls)
{
    category_list *cats;
    bool isMeta;

    runtimeLock.assertWriting();

    isMeta = cls->isMetaClass();

    // Re-methodizing: check for more categories
    if ((cats = unattachedCategoriesForClass(cls, false/*not realizing*/))) {
        if (PrintConnecting) {
            _objc_inform("CLASS: attaching categories to class '%s' %s", 
                         cls->nameForLogging(), isMeta ? "(meta)" : "");
        }
        
        attachCategories(cls, cats, true /*flush caches*/);        
        free(cats);
    }
}

該段代碼首先通過unattachedCategoriesForClass 取出還未被附加到class上的category list,然后調用attachCategories將這些category附加到class上。

attachCategories 的實現如下:

// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order, 
// oldest categories first.
static void 
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
    if (!cats) return;
    if (PrintReplacedMethods) printReplacements(cls, cats);

    bool isMeta = cls->isMetaClass();

    // 首先分配method_list_t *, property_list_t *, protocol_list_t *的數組空間,數組大小等于category的個數
    method_list_t **mlists = (method_list_t **)
        malloc(cats->count * sizeof(*mlists));
    property_list_t **proplists = (property_list_t **)
        malloc(cats->count * sizeof(*proplists));
    protocol_list_t **protolists = (protocol_list_t **)
        malloc(cats->count * sizeof(*protolists));

    // Count backwards through cats to get newest categories first
    int mcount = 0;
    int propcount = 0;
    int protocount = 0;
    int i = cats->count;
    bool fromBundle = NO;
    while (i--) {  // 依次讀取每一個category,將其methods,property,protocol添加到mlists,proplist,protolist中存儲
        auto& entry = cats->list[I];

        method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        if (proplist) {
            proplists[propcount++] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocols;
        if (protolist) {
            protolists[protocount++] = protolist;
        }
    }

    // 取出class的data()數據,其實是class_rw_t * 指針,其對應結構體實例存儲了class的基本信息
    auto rw = cls->data();

    prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
    rw->methods.attachLists(mlists, mcount);  // 將category中的method 添加到class中
    free(mlists);
    if (flush_caches  &&  mcount > 0) flushCaches(cls); // 如果需要,同時刷新class的method list cache


    rw->properties.attachLists(proplists, propcount); // 將category的property添加到class中
    free(proplists);

    rw->protocols.attachLists(protolists, protocount); // 將category的protocol添加到class中
    free(protolists);
}

到此為止,我們就完成了category的加載工作。可以看到,最終,cateogry被加入到了對應class的方法,協議以及屬性列表中。

最后我們再看一下attachLists方法是如何將兩個list合二為一的:

   void attachLists(List* const * addedLists, uint32_t addedCount) {
        if (addedCount == 0) return;

        if (hasArray()) {
            // many lists -> many lists
            uint32_t oldCount = array()->count;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
            array()->count = newCount;
            memmove(array()->lists + addedCount, array()->lists, 
                    oldCount * sizeof(array()->lists[0]));
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
        else if (!list  &&  addedCount == 1) {
            // 0 lists -> 1 list
            list = addedLists[0];
        } 
        else {
            // 1 list -> many lists
            List* oldList = list;
            uint32_t oldCount = oldList ? 1 : 0;
            uint32_t newCount = oldCount + addedCount;
            setArray((array_t *)malloc(array_t::byteSize(newCount)));
            array()->count = newCount;
            if (oldList) array()->lists[addedCount] = oldList;
            memcpy(array()->lists, addedLists, 
                   addedCount * sizeof(array()->lists[0]));
        }
    }

仔細看會發現,attachLists方法其實是使用的‘頭插’的方式將新的list插入原有list中的。即,新的list會插入到原始list的頭部。

<font color=orange>這也就說明了,為什么category中的方法,會‘覆蓋’class的原始方法。其實并沒有真正的‘覆蓋’,而是由于cateogry中的方法被排到了原始方法的前面,那么在消息查找流程中,會返回首先被查找到的cateogry方法的實現。</font>

category和+load方法

在面試時,可能被問到這樣的問題:

在類的+load方法中,可以調用分類方法嗎?

要回答這個問題,其實要搞清load方法的調用時機和category附加到class上的先后順序。

如果在load方法被調用前,category已經完成了附加到class上的流程,則對于上面的問題,答案是肯定的。

我們回到runtime的入口函數來看一下,

void _objc_init(void)
{
    static bool initialized = false;
    if (initialized) return;
    initialized = true;
    
    // fixme defer initialization until an objc-using image is found?
    environ_init();
    tls_init();
    static_init();
    lock_init();
    exception_init();

    _dyld_objc_notify_register(&map_images, load_images, unmap_image);
}

runtime在入口點分別向dyld注冊了三個事件監聽:mapped oc sections, init oc section 以及 unmapped oc sections。

而這三個事件的順序是: mapped oc sections -> init oc section -> unmapped oc sections

mapped oc sections 事件中,我們已經看過其源碼,runtime會依次讀取Mach-O文件中的oc sections,并根據這些信息來初始化runtime環境。這其中就包括cateogry的加載。

之后,當runtime環境都初始化完畢,在dyld的init oc section 事件中,runtime會調用每一個加載到內存中的類的+load方法。

這里我們注意到,+load方法的調用是在cateogry加載之后的。因此,在+load方法中,是可以調用category方法的。

調用已被category‘覆蓋’的方法

前面我們已經知道,類中的方法并不是真正的被category‘覆蓋’,而是被放到了類方法列表的后面,消息查找時找不到而已。我們當然也可以手動來找到并調用它,代碼如下:

@interface Son : NSObject
- (void)sayHi;
@end

@implementation Son
- (void)sayHi {
    NSLog(@"Son say hi!");
}
@end

// son 的分類,覆寫了sayHi方法
@interface Son (Good)
- (void)sayHi;
- (void)saySonHi;
@end

- (void)sayHi {
    NSLog(@"Son's category good say hi");
}

- (void)saySonHi {
    unsigned int methodCount = 0;
    Method *methodList = class_copyMethodList([self class], &methodCount);
    
    SEL sel = @selector(sayHi);
    NSString *originalSelName = NSStringFromSelector(sel);
    IMP lastIMP = nil;
    for (NSInteger i = 0; i < methodCount; ++i) {
        Method method = methodList[I];
        NSString *selName = NSStringFromSelector(method_getName(method));
        if ([originalSelName isEqualToString:selName]) {
            lastIMP = method_getImplementation(method);
        }
    }
    
    if (lastIMP != nil) {
        typedef void(*fn)(id, SEL);
        fn f = (fn)lastIMP;
        f(self, sel);
    }
    free(methodList);
    
}

// 分別調用sayHi 和 saySonHi
Son *mySon1 = [Son new];
[mySon1 sayHi];
[mySon1 saySonHi];

輸出為:

這里寫圖片描述

果然,我們調用到了原始的sayHi方法。

category和關聯對象

眾所周知,category是不支持向類添加實例變量的。這在源碼中也可以看出,cateogry僅支持實例方法、類方法、協議、和實例屬性(注意,實例屬性并不等于實例變量)。

但是,runtime也給我提供了一個折中的方式,雖然不能夠向類添加實例變量,但是runtime為我們提供了方法,可以向類的實例對象添加關聯對象。

所謂關聯對象,就是為目標對象添加一個關聯的對象,并能夠通過key來查找到這個關聯對象。說的形象一點,就像我們去跳舞,runtime可以給我們分配一個舞伴一樣。

這種關聯是對象和對象級別的,而不是類層次上的。當你為一個類實例添加一個關聯對象后,如果你再創建另一個類實例,這個新建的實例是沒有關聯對象的。

我們可以通過重寫set/get方法的形式,來自動為我們的實例添加關聯對象。

MyClass+Category1.h:

#import "MyClass.h"

@interface MyClass (Category1)

@property(nonatomic,copy) NSString *name;

@end

MyClass+Category1.m:

#import "MyClass+Category1.h"
#import <objc/runtime.h>

@implementation MyClass (Category1)

+ (void)load
{
    NSLog(@"%@",@"load in Category1");
}

- (void)setName:(NSString *)name
{
    objc_setAssociatedObject(self,
                             "name",
                             name,
                             OBJC_ASSOCIATION_COPY);
}

- (NSString*)name
{
    NSString *nameObject = objc_getAssociatedObject(self, "name");
    return nameObject;
}

@end

代碼很簡單,我們重點關注一下其背后的實現。

objc_setAssociatedObject

我們要設置關聯對象,需要調用objc_setAssociatedObject 方法將對象關聯到目標對象上。我們需要傳入4個參數:target object, associated key, associated value, objc_AssociationPolicy。

objc_AssociationPolicy是一個枚舉,可以取值為:

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

分別和property的屬性定義一一匹配。

當我們為對象設置關聯對象的時候,所關聯的對象到底存在了那里呢?我們看源碼:

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
    _object_set_associative_reference(object, (void *)key, value, policy);
}
void _object_set_associative_reference(id object, void *key, id value, uintptr_t policy) {
    // retain the new value (if any) outside the lock.
    ObjcAssociation old_association(0, nil);
    id new_value = value ? acquireValue(value, policy) : nil;
    {
        AssociationsManager manager; // 這是一個單例,內部保存一個全局的static AssociationsHashMap *_map; 用于保存所有的關聯對象。
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object); // 取反object 地址 作為accociative key
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i != associations.end()) {
                // secondary table exists
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    j->second = ObjcAssociation(policy, new_value);
                } else {
                    (*refs)[key] = ObjcAssociation(policy, new_value);
                }
            } else {
                // create the new association (first time).
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects(); // 將object標記為 has AssociatedObjects
            }
        } else { // 如果傳入的關聯對象值為nil,則斷開關聯
            // setting the association to nil breaks the association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            if (i !=  associations.end()) {
                ObjectAssociationMap *refs = i->second;
                ObjectAssociationMap::iterator j = refs->find(key);
                if (j != refs->end()) {
                    old_association = j->second;
                    refs->erase(j);
                }
            }
        }
    }
    // release the old value (outside of the lock).
    if (old_association.hasValue()) ReleaseValue()(old_association); // 釋放掉old關聯對象。(如果多次設置同一個key的value,這里會釋放之前的value)
}

大體流程為:

  1. 根據關聯的policy,調用id new_value = value ? acquireValue(value, policy) : nil;acquireValue 方法會根據poilcy是retain或copy,對value做引用+1操作或copy操作,并返回對應的new_value。(如果傳入的value為nil,則返回nil,不做任何操作)
    acquireValue實現代碼是:
static id acquireValue(id value, uintptr_t policy) {
    switch (policy & 0xFF) {
    case OBJC_ASSOCIATION_SETTER_RETAIN:
        return objc_retain(value);
    case OBJC_ASSOCIATION_SETTER_COPY:
        return ((id(*)(id, SEL))objc_msgSend)(value, SEL_copy);
    }
    return value;
}
  1. 獲取到new_value 后,根據是否有new_value的值,進入不同流程。如果 new_value 存在,則對象與目標對象關聯。實質是存入到全局單例 AssociationsManager manager 的對象關聯表中。 如果new_value 不存在,則釋放掉之前目標對象及關聯 key所存儲的關聯對象。實質是在 AssociationsManager 中刪除掉關聯對象。
  2. 最后,釋放掉之前以同樣key存儲的關聯對象。

其中,起到關鍵作用的在于AssociationsManager manager, 它是一個全局單例,其成員變量為static AssociationsHashMap *_map,用于存儲目標對象及其關聯的對象。_map中的數據存儲結構如下圖所示:

這里寫圖片描述

仔細看這一段代碼,會發現有個問題:當我們第一次為目標對象創建關聯對象時,會在AssociationsManager managerObjectAssociationMap 中插入一個以disguised_object為key 的節點,用于存儲該目標對象所關聯的對象。

但是,上面代碼中,僅有釋放old_association關聯對象的代碼,而沒有釋放保存在AssociationsManager manager 中節點的代碼。那么,AssociationsManager manager 中的節點是什么時候被釋放的呢?

在對象的銷毀邏輯里,會調用objc_destructInstance,實現如下:

void *objc_destructInstance(id obj) 
{
    if (obj) {
        // Read all of the flags at once for performance.
        bool cxx = obj->hasCxxDtor();
        bool assoc = obj->hasAssociatedObjects();

        // This order is important.
        if (cxx) object_cxxDestruct(obj); // 調用C++析構函數
        if (assoc) _object_remove_assocations(obj); // 移除所有的關聯對象,并將其自身從AssociationsManager的map中移除
        obj->clearDeallocating(); // 清理ARC ivar
    }

    return obj;
}

obj的關聯對象會在_object_remove_assocations方法中全部移除,同時,會將obj自身從AssociationsManagermap中移除:

void _object_remove_assocations(id object) {
    vector< ObjcAssociation,ObjcAllocator<ObjcAssociation> > elements;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        if (associations.size() == 0) return;
        disguised_ptr_t disguised_object = DISGUISE(object);
        AssociationsHashMap::iterator i = associations.find(disguised_object);
        if (i != associations.end()) {
            // copy all of the associations that need to be removed.
            ObjectAssociationMap *refs = i->second;
            for (ObjectAssociationMap::iterator j = refs->begin(), end = refs->end(); j != end; ++j) {
                elements.push_back(j->second);
            }
            // remove the secondary table.
            delete refs;
            associations.erase(i);
        }
    }
    // the calls to releaseValue() happen outside of the lock.
    for_each(elements.begin(), elements.end(), ReleaseValue());
}

參考文獻

深入理解Objective-C:Category

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容