??運行期不能對類對象添加ivar
捡需,因為在編譯期類的內(nèi)存大小布局已經(jīng)確定哀卫,在運行期不能修改類對象的內(nèi)存空間,所以不能在運行期為對象添加ivar
矾兜,比如不能在category
中添加ivar
,而category
是運行期技術(shù)巩检,但可以添加方法厚骗,因為類對象內(nèi)的方法列表是指針,添加方法改變的是指針指向的方法列表兢哭,沒有改變指針本身领舰,不會改變類對象內(nèi)存大小,所以category
可以添加方法迟螺。
??有一點需要說明雖然category
添加屬性冲秽,但不會為這個屬性自動添加ivar
,只會生成setter
和getter
方法的聲明矩父。
??所以添加屬性的方法只能用objc_setAssociatedObject
方式锉桑,下面重點講述objc_setAssociatedObject
和objc_getAssociatedObject
實現(xiàn)原理。
先看看objc_setAssociatedObject
方法參數(shù)說明窍株。
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
* @see objc_setAssociatedObject
* @see objc_removeAssociatedObjects
*/
這里要講的是key這個參數(shù)其實是個指針值民轴,只要保證指針值不一樣就行,就算指針指向的對象值相等也沒關(guān)系夹姥,有一種很優(yōu)雅的寫法:
objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
_cmd
代表當前方法的SEL
杉武,相當于這么寫@selector(currentMethod)
,SEL
其實就是個指針辙售,而且能保證唯一。
現(xiàn)在看一下objc_setAssociatedObject
的實現(xiàn)
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) {
_object_set_associative_reference(object, (void *)key, value, policy);
}
直接調(diào)用了_object_set_associative_reference
飞涂,往下看吧:
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);
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();
}
} else {
// 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);
}
AssociationsManager manager
是個c++對象旦部,維護一個全局唯一單例hashmap,并且在構(gòu)造函數(shù)加鎖和析構(gòu)函數(shù)解鎖保證hashmap操作時的安全性较店,全局hashmap先根據(jù)當前object(key:DISGUISE(object))
查找ObjectAssociationMap
士八,ObjectAssociationMap
存放的是ObjcAssociation
對象,其實是對要存放的value
和policy
的簡單封裝梁呈,可以看下ObjcAssociation
的定義婚度;
class ObjcAssociation {
uintptr_t _policy;
id _value;
public:
ObjcAssociation(uintptr_t policy, id value) : _policy(policy), _value(value) {}
ObjcAssociation() : _policy(0), _value(nil) {}
uintptr_t policy() const { return _policy; }
id value() const { return _value; }
bool hasValue() { return _value != nil; }
};
哎,也是class
官卡;
所以全局hashmap是個二維的map蝗茁,ObjectAssociationMap
如果沒找到創(chuàng)建一個新的ObjectAssociationMap
然后將new_value添加到map里,找到了ObjectAssociationMap
再根據(jù)參數(shù)key找舊值寻咒,找到了更新舊值為新的值哮翘,沒找到將new_value添加到map里。
整個查找過程是個兩層的遍歷毛秘。
看懂這塊代碼就明白:
通過objc_setAssociatedObject
添加屬性實際上是系統(tǒng)維護了一個全局的二維map饭寺,將對象與要添加的屬性進行map的鍵值綁定阻课。
_policy的作用在于是否需要在方法開始retain value,如果是retain policy則需要retain objc_retain(value)
如果是copy則調(diào)用value的copy
方法((id(*)(id, SEL))objc_msgSend)(value, SEL_copy)
;并且需要在方法結(jié)束時Relase艰匙,看下面的方法
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;
}
看完objc_setAssociatedObject
就知道objc_getAssociatedObject
是怎么實現(xiàn)的了限煞,不多說了。
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;
}
最后在說一個小問題代碼中 disguised_ptr_t disguised_object = DISGUISE(object)
员凝,disguised_object
作為全局map的key值署驻,并不是吧object作為key值,disguised_object
是怎么得來的需要看下代碼DISGUISE
方法實現(xiàn)
inline disguised_ptr_t DISGUISE(id value) { return ~uintptr_t(value); }
哦很簡單绊序,object
是個指針地址硕舆,把它強轉(zhuǎn)成uintptr_t
(實際上是long
類型)然后進行取反操作。