??運(yùn)行期不能對(duì)類對(duì)象添加ivar,因?yàn)樵诰幾g期類的內(nèi)存大小布局已經(jīng)確定,在運(yùn)行期不能修改類對(duì)象的內(nèi)存空間,所以不能在運(yùn)行期為對(duì)象添加ivar,比如不能在category中添加ivar,而category是運(yùn)行期技術(shù),但可以添加方法,因?yàn)轭悓?duì)象內(nèi)的方法列表是指針,添加方法改變的是指針指向的方法列表,沒有改變指針本身,不會(huì)改變類對(duì)象內(nèi)存大小,所以category可以添加方法。
??有一點(diǎn)需要說明雖然category添加屬性,但不會(huì)為這個(gè)屬性自動(dòng)添加ivar,只會(huì)生成setter和getter方法的聲明。
??所以添加屬性的方法只能用objc_setAssociatedObject方式,下面重點(diǎn)講述objc_setAssociatedObject和objc_getAssociatedObject實(shí)現(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這個(gè)參數(shù)其實(shí)是個(gè)指針值,只要保證指針值不一樣就行,就算指針指向的對(duì)象值相等也沒關(guān)系,有一種很優(yōu)雅的寫法:
objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
_cmd代表當(dāng)前方法的SEL,相當(dāng)于這么寫@selector(currentMethod),SEL其實(shí)就是個(gè)指針,而且能保證唯一。
現(xiàn)在看一下objc_setAssociatedObject的實(shí)現(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是個(gè)c++對(duì)象,維護(hù)一個(gè)全局唯一單例hashmap,并且在構(gòu)造函數(shù)加鎖和析構(gòu)函數(shù)解鎖保證hashmap操作時(shí)的安全性,全局hashmap先根據(jù)當(dāng)前object(key:DISGUISE(object))查找ObjectAssociationMap,ObjectAssociationMap存放的是ObjcAssociation對(duì)象,其實(shí)是對(duì)要存放的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是個(gè)二維的map,ObjectAssociationMap如果沒找到創(chuàng)建一個(gè)新的ObjectAssociationMap然后將new_value添加到map里,找到了ObjectAssociationMap再根據(jù)參數(shù)key找舊值,找到了更新舊值為新的值,沒找到將new_value添加到map里。
整個(gè)查找過程是個(gè)兩層的遍歷。
看懂這塊代碼就明白:
通過objc_setAssociatedObject添加屬性實(shí)際上是系統(tǒng)維護(hù)了一個(gè)全局的二維map,將對(duì)象與要添加的屬性進(jìn)行map的鍵值綁定。
_policy的作用在于是否需要在方法開始retain value,如果是retain policy則需要retain objc_retain(value)如果是copy則調(diào)用value的copy方法((id(*)(id, SEL))objc_msgSend)(value, SEL_copy);并且需要在方法結(jié)束時(shí)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是怎么實(shí)現(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;
}
最后在說一個(gè)小問題代碼中 disguised_ptr_t disguised_object = DISGUISE(object),disguised_object作為全局map的key值,并不是吧object作為key值,disguised_object是怎么得來的需要看下代碼DISGUISE方法實(shí)現(xiàn)
inline disguised_ptr_t DISGUISE(id value) { return ~uintptr_t(value); }
哦很簡單,object是個(gè)指針地址,把它強(qiáng)轉(zhuǎn)成uintptr_t(實(shí)際上是long類型)然后進(jìn)行取反操作。