RunTime源碼閱讀(二)關(guān)聯(lián)對象

1. 三個方法

objc_setAssociatedObject
objc_getAssociatedObject
objc_removeAssociatedObjects

2原理

2.1objc_setAssociatedObject

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;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        if (new_value) {
            // break any existing association.
            AssociationsHashMap::iterator i = associations.find(disguised_object);
            //同一個對象只會創(chuàng)建一個ObjectAssociationMap對象。蜈彼?
            if (i != associations.end()) {
                // secondary table exists
                //當(dāng)前對象已經(jīng)創(chuàng)建關(guān)聯(lián)對象時
                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);//對象置nil后再關(guān)聯(lián)對象
                }
            } else {
                // create the new association (first time).
                //當(dāng)前對象沒有創(chuàng)建關(guān)聯(lián)對象時
                ObjectAssociationMap *refs = new ObjectAssociationMap;
                associations[disguised_object] = refs;
                (*refs)[key] = ObjcAssociation(policy, new_value);
                object->setHasAssociatedObjects();
            }
        } else {
            // setting the association to nil breaks the association.
            // 當(dāng)前對象value設(shè)置為nil時杂数,釋放ObjectAssociationMap對象
            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);
}

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. 全局維護AssociationsManager,管理類中存放的是AssociationsHashMap晰韵。
  2. acquireValue如果是OBJC_ASSOCIATION_SETTER_RETAIN或OBJC_ASSOCIATION_SETTER_COPY靡砌,對value進行retain和copy操作。與引用計數(shù)管理相同。
  3. 存儲時跟匆,通過DISGUISE(object)作為key查找,associations沒有存儲時會走else
ObjectAssociationMap *refs = new ObjectAssociationMap;
 associations[disguised_object] = refs;
 (*refs)[key] = ObjcAssociation(policy, new_value);
object->setHasAssociatedObjects();

inline void
objc_object::setHasAssociatedObjects()
{
    ...
    newisa.has_assoc = true;//關(guān)聯(lián)對象標(biāo)志位
    if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
}

ObjcAssociation是構(gòu)造存儲對象通砍。
即一個對象會生成一個ObjectAssociationMap玛臂,并通過disguised_object存儲在associations中,new_value存儲在ref中封孙,setHasAssociatedObjects設(shè)置對象有關(guān)聯(lián)對象的標(biāo)志位迹冤。
refs存儲當(dāng)前對象的所有關(guān)聯(lián)對象

  1. associations已經(jīng)分配時,通過key進行存儲
ObjectAssociationMap *refs = i->second;
ObjectAssociationMap::iterator j = refs->find(key);
if (j != refs->end()) {
     old_association = j->second;
     j->second = ObjcAssociation(policy, new_value);//key已經(jīng)存在時敛瓷,找到對應(yīng)位置更新舊的
} else {
     (*refs)[key] = ObjcAssociation(policy, new_value);//key沒有存儲時叁巨,直接存儲
}

如果key存儲過值,找到對應(yīng)的value的位置呐籽,替換舊的锋勺。
如果key沒有,ObjcAssociation構(gòu)造的對象狡蝶。

關(guān)聯(lián)對象存儲分三種情況:
第一種:對象第一次使用關(guān)聯(lián)對象初始化庶橱,ObjectAssociationMap,使用策略和value構(gòu)造存儲對象
第二種:對象的關(guān)聯(lián)對象已經(jīng)初始化贪惹,在ObjectAssociationMap查找苏章,沒找到按key直接存儲。
第三種:對象的關(guān)聯(lián)對象已經(jīng)初始化奏瞬,在ObjectAssociationMap查找枫绅,找到按key替換原有的存儲。

2.2 objc_getAssociatedObject

id objc_getAssociatedObject(id object, const void *key) {
    return _object_get_associative_reference(object, (void *)key);
}

id _object_get_associative_reference(id object, void *key) {
    id value = nil;
    uintptr_t policy = OBJC_ASSOCIATION_ASSIGN;
    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.associations());
        disguised_ptr_t disguised_object = DISGUISE(object);
        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()) {
                ObjcAssociation &entry = j->second;
                value = entry.value();
                policy = entry.policy();
                if (policy & OBJC_ASSOCIATION_GETTER_RETAIN) {
                    objc_retain(value);
                }
            }
        }
    }
    if (value && (policy & OBJC_ASSOCIATION_GETTER_AUTORELEASE)) {
        objc_autorelease(value);
    }
    return value;
}

這一段在associations查找硼端,如果策略是OBJC_ASSOCIATION_GETTER_RETAIN并淋,會有個計數(shù)+1objc_retain(value);如果是OBJC_ASSOCIATION_GETTER_AUTORELEASE,通過objc_autorelease延遲釋放珍昨。

2.3objc_removeAssociatedObjects

void objc_removeAssociatedObjects(id object) 
{
    if (object && object->hasAssociatedObjects()) {
        _object_remove_assocations(object);
    }
}

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());
}

這個方法在dealloc中通過hasAssociatedObjects標(biāo)志位釋放县耽,
找到關(guān)聯(lián)對象elements,遍歷進行釋放镣典。

總結(jié):
1.不用修改原有對象就能為其添加屬性兔毙,不消耗對象分配空間。
2.關(guān)聯(lián)對象釋放不用擔(dān)心兄春,系統(tǒng)會在對象銷毀時在dealloc中根據(jù)標(biāo)志位進行釋放澎剥。
3.關(guān)聯(lián)對象與分類的關(guān)系?關(guān)聯(lián)對象很好的解決了分類不能添加屬性的問題赶舆。
4.關(guān)聯(lián)對象的本質(zhì):由AssociationsManager管理并在AssociationsHashMap存儲哑姚。
所有對象的關(guān)聯(lián)內(nèi)容都在同一個全局容器中趾唱。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蜻懦,隨后出現(xiàn)的幾起案子甜癞,更是在濱河造成了極大的恐慌,老刑警劉巖宛乃,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悠咱,死亡現(xiàn)場離奇詭異,居然都是意外死亡征炼,警方通過查閱死者的電腦和手機析既,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來谆奥,“玉大人眼坏,你說我怎么就攤上這事∷嵝” “怎么了宰译?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長魄懂。 經(jīng)常有香客問我沿侈,道長,這世上最難降的妖魔是什么市栗? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任缀拭,我火速辦了婚禮,結(jié)果婚禮上填帽,老公的妹妹穿的比我還像新娘蛛淋。我一直安慰自己,他們只是感情好篡腌,可當(dāng)我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布褐荷。 她就那樣靜靜地躺著,像睡著了一般哀蘑。 火紅的嫁衣襯著肌膚如雪诚卸。 梳的紋絲不亂的頭發(fā)上葵第,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天绘迁,我揣著相機與錄音,去河邊找鬼卒密。 笑死缀台,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哮奇。 我是一名探鬼主播膛腐,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼睛约,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了哲身?” 一聲冷哼從身側(cè)響起辩涝,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎勘天,沒想到半個月后怔揩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡脯丝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年商膊,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宠进。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡晕拆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出材蹬,到底是詐尸還是另有隱情实幕,我是刑警寧澤,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布堤器,位于F島的核電站茬缩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏吼旧。R本人自食惡果不足惜凰锡,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望圈暗。 院中可真熱鬧掂为,春花似錦、人聲如沸员串。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽寸齐。三九已至欲诺,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間渺鹦,已是汗流浹背扰法。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留毅厚,地道東北人塞颁。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親祠锣。 傳聞我的和親對象是個殘疾皇子酷窥,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容