上周写了篇关于iOS 分类的文章,我们可以在分类中定义属性,但只是定义了属性,编译器既没有生成相应的setter和getter方法,也没有生成对应的成员属性。如果想给对象动态添加属性就需要用到runtime库中的API了
我们给一个类动态添加属性的做法如下:
@interface Person (Test1)
@property (nonatomic, strong) NSString *name;
@end
@implementation Person (Test1)
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name {
return objc_getAssociatedObject(self, @selector(name));
}
@end
尝试给Person对象设置name属性,再打印Person对象的name属性看看是不是我们刚刚设置的值
打印结果表明,我们给Person实例对象关联的name属性真的设置了,并且不同对象之间关联的属性也互不影响。
我们都很肯定关联的属性值不是存放在实例对象结构中的,因为实例对象的结构在编译时就确定的,而属性关联却是在运行时动态关联的。objc_setAssociatedObject(...)和objc_getAssociatedObject(...)这两个方法都需要2个参数,分别是需要关联属性的对象self和属性对应的key。两个方法都需要传key过去,而且这两个方法的key要一样,因此猜测底层存储的方式为map(runtime库是C/C++)
课前小菜
在阅读源码之前,我们首先要理解几个关键的C++类
- 1. AssociationsManager
spinlock_t AssociationsManagerLock;
class AssociationsManager {
// associative references: object pointer -> PtrPtrHashMap.
static AssociationsHashMap *_map;
public:
AssociationsManager() { AssociationsManagerLock.lock(); }
~AssociationsManager() { AssociationsManagerLock.unlock(); }
AssociationsHashMap &associations() {
if (_map == NULL)
_map = new AssociationsHashMap();
return *_map;
}
};
AssociationsHashMap *AssociationsManager::_map = NULL;
我将AssociationsManager称之为管理对象,其内部有一个AssociationsHashMap类型的静态指针变量_map,这个变量在程序运行期间只有一份。而从AssociationsManager的构造函数和析构函数中猜测该类存在的意义是维持一个原子锁,确保在程序运行期间,内存中只存在一个AssociationsManager类型的对象。
- 2. AssociationsHashMap
typedef ObjcAllocator<std::pair<const disguised_ptr_t, ObjectAssociationMap*> > AssociationsHashMapAllocator;
class AssociationsHashMap : public unordered_map<disguised_ptr_t, ObjectAssociationMap *, DisguisedPointerHash, DisguisedPointerEqual, AssociationsHashMapAllocator> {
public:
void *operator new(size_t n) { return ::malloc(n); }
void operator delete(void *ptr) { ::free(ptr); }
};
在objc-references.mm文件中对AssociationsHashMap类的定义分成了win32架构和其他架构,由于iOS目前仅可发布arm64架构的,因此这里只截取了64架构的源码,有兴趣了解win32位的实现的同学可自行查阅相关源码。
AssociationsHashMap类继承自unordered_map,unordered_map和map都是存储键值对的容器,但map底层是红黑树存储方式,存储顺序为key有序序列。而unordered_map则是无序,哈希表存储方式。
AssociationsHashMap中的key类型为disguised_ptr_t,value类型为ObjectAssociationMap类型的指针,key的哈希算法为DisguisedPointerHash,key判断函数为DisguisedPointerEqual,键值对内存分配器为AssociationsHashMapAllocator
3. ObjectAssociationMap
typedef ObjcAllocator<std::pair<void * const, ObjcAssociation> > ObjectAssociationMapAllocator;
class ObjectAssociationMap : public std::map<void *, ObjcAssociation, ObjectPointerLess, ObjectAssociationMapAllocator> {
public:
void *operator new(size_t n) { return ::malloc(n); }
void operator delete(void *ptr) { ::free(ptr); }
};
ObjectAssociationMap继承自map,和AssociationsHashMap一样都是键值对存储。key的类型对指针,value为ObjcAssociation,key的判断函数为ObjectPointerLess,键值对内存分配器为ObjectAssociationMapAllocator。
4. ObjectAssociationMap
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; }
};
ObjcAssociation类中只有2个成员属性,_policy和_value。通过名字我们可以猜到这个类主要存储的是关联的值和关联策略。
正菜
objc_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);
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);
}
- 首先根据关联策略决定对关联值还是引用计数器+1,亦或是拷贝关联值
- 初始化AssociationsManager对象,若此时正有另一个对象在做关联操作,则当前AssociationsManager对象的初始化方法会被阻塞。在同一时间中,有且仅有一个AssociationsManager实例对象存在在内存中,即同一时间只有一个对象在进行关联操作
- 获取AssociationsManager中的静态变量AssociationsHashMap
- 调用DISGUISE()函数获取对象地址的反码disguised_object
- 将对象地址的反码作为key,在AssociationsHashMap哈希表中查找key为disguised_object的ObjectAssociationMap类型的对象
- 如果找到ObjectAssociationMap,则继续根据我们传入的关联key继续在ObjectAssociationMap表中查找对应的ObjcAssociation对象,并替换成新的ObjcAssociation对象
- 如果在第6步中没找到ObjcAssociation,则新建一个ObjcAssociation对象,并和关联key绑定
- 如果在第5步中没有找到ObjectAssociationMap ,则创建一个ObjectAssociationMap,把对应的ObjcAssociation和key存储起来
- 如果我们设置的value为nil,对应的操作是从对象的关联哈希表ObjectAssociationMap中删除key对应的ObjcAssociation对象
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;
}
- 初始化AssociationsManager对象,若此时正有另一个对象在做关联操作,则同样**AssociationsManager****对象的初始化方法会被阻塞
- 获取AssociationsManager中的静态变量AssociationsHashMap
- 调用DISGUISE函数获取对象地址的反码disguised_object
- 将对象地址的反码作为key,在AssociationsHashMap哈希表中查找key为disguised_object的ObjectAssociationMap类型的对象
- 如果在第4步中找到ObjectAssociationMap,则继续根据我们传入的关联key继续在ObjectAssociationMap表中查找对应的ObjcAssociation对象,如果找到了,取出其中的value
- 如果在第5步中没找到ObjcAssociation,则该key不存在关联的值
- 如果在第4步中没有找到ObjectAssociationMap ,则该对象没有设置过关联属性
- 根据关联策略决定是否对查询到的value进行retain操作或则autorelease
沙拉
文笔不是很好,👆的这段话应该很难理解了,没关系,把关系图画出来就容易理解了。
AssociationsManager可重复创建,但是AssociationsHashMap是AssociationsManager内的静态变量,全局只有一个,负责管理所有对象的关联表。通过对象地址的反码取出该对象的属性关联表ObjectAssociationMap。然后再通过关联key从对象关联表中获取对应的ObjectAssociation,ObjectAssociation内存储的就是真正需要的存储的value值和内存关联策略policy了。
如果想删除对象关联的某一个value值,可传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);
}
}
甜点
在对象释放的时候,会判断对象是否关联过属性,如果关联过属性,则会调用_object_remove_assocations删除其在AssociationsHashMap中对应的值ObjectAssociationMap和ObjectAssociationMap中的每个ObjectAssociation。
// - (void)dealloc; (NSObject.mm)
// void_objc_rootDealloc(id obj); (NSObject.mm)
// inline void objc_object::rootDealloc(); (objc-object.h)
// id object_dispose(id obj); (objc-runtime-new.mm)
// void *objc_destructInstance(id obj); (objc-runtime-new.mm)
// void _object_remove_assocations(id object) (objc-references.mm)
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());
}
在_object_set_associative_reference()函数中,当为对象创建ObjectAssociationMap哈希表的时候,也会调用objc_object::setHasAssociatedObjects()将对象ISA指针的第二位has_assoc设置为1。这一步只要设置了之后,直到被释放,第二位has_assoc都为1。
Tips:在iOS arm64位系统中,ISA指针是经过优化的,采用了共同体,可存储更多的信息。而ISA指针的第2位0和1分别表示该对象是否关联过对象
union isa_t
{
isa_t() { }
isa_t(uintptr_t value) : bits(value) { }
Class cls;
uintptr_t bits;
# if __arm64__
# define ISA_MASK 0x0000000ffffffff8ULL
# define ISA_MAGIC_MASK 0x000003f000000001ULL
# define ISA_MAGIC_VALUE 0x000001a000000001ULL
struct {
uintptr_t nonpointer : 1;
uintptr_t has_assoc : 1;
uintptr_t has_cxx_dtor : 1;
uintptr_t shiftcls : 33; // MACH_VM_MAX_ADDRESS 0x1000000000
uintptr_t magic : 6;
uintptr_t weakly_referenced : 1;
uintptr_t deallocating : 1;
uintptr_t has_sidetable_rc : 1;
uintptr_t extra_rc : 19;
# define RC_ONE (1ULL<<45)
# define RC_HALF (1ULL<<18)
};
# elif __x86_64__
...
#endif
};
验证一下关联属性前后ISA指针第二位has-assoc的变化
在没关联之前,ISA指针的第二位has_assoc的为0,在关联属性之后,ISA指针的第二位has_assoc变为了1。
这次写的不是很好,理解起来会有点困难,本人也还在继续提升写作能力,望谅解