why
一般情况下,weak修饰对象,assign修饰基本数据类型。
weak和assign,并不会增加对象的rcassign修饰的对象,出栈后,对象所指向的内存块极有可能被回收,如果此时再访问指针,会出现野指针的情况weak修饰的对象,因为weak所修饰的对象被系统回收之后,指针会被置为nil,不会出现也指针
下面会从源码中一探究竟。(源码的版本是objc4-723)
weak 源码
源码中出现的数据结构
SideTables
1 | static StripedMap<SideTable>& SideTables() { |
SideTable
1 | struct SideTable { |
RefcountMap:引用计数表weak_table_t:
1 | struct weak_table_t { |
先来看一下源码的注释,理解一下做法。
1 | // Update a weak variable. |
- 这个接口是用来更新weak变量的
- 如果HaveOld是ture,weak变量已经指向了某个对象,就先清除这个对象,然后指向新的对象,这个对象可能是nil
- 如果HaveNew是ture 有新的对象来替换,那么要将这个对象存起来。这个新的对象可能是nil
- 如果crashifdeallocation是ture,那么如果指向的对象已经被释放或者该对象不支持weak引用,这个进程会停止
- 如果crashifdeallocation是false,nil会被储存起来
然后祭出源码
1 | id |
检查是否有新值或旧值(haveOld==false&&haveNew==false的情况可能发生吗?)1
assert(haveOld || haveNew);
如果没有新值,判断传入的newObj1
if (!haveNew) assert(newObj == nil);
创建两张表1
2SideTable *oldTable;
SideTable *newTable;
1 | * 如果有旧值,以oldObj为索引 从SideTables取出相应的结构体 |
判断cls是否为空以及是否初始化1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19if (cls != previouslyInitializedClass &&
!((objc_class *)cls)->isInitialized())
{
//解锁
SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
// 初始化
_class_initialize(_class_getNonMetaClass(cls, (id)newObj));
// If this class is finished with +initialize then we're good.
// If this class is still running +initialize on this thread
// (i.e. +initialize called storeWeak on an instance of itself)
// then we may proceed but it will appear initializing and
// not yet initialized to the check above.
// Instead set previouslyInitializedClass to recognize it on retry.
//更新初始化过的cls
previouslyInitializedClass = cls;
goto retry;
}
清除旧值1
2
3if (haveOld) {
weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
}
分配新值
1 | // Assign new value, if any. |
处理完成后1
2
3
4//解锁
SideTable::unlockTwo<haveOld, haveNew>(oldTable, newTable);
//返回newObj
return (id)newObj;
相关细节:
weak_unregister_no_lock 移除旧的指针:
objc-weak.mm line 3481
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39//weak_table referent_id要指向的对象 *referrer_id指针
void
weak_unregister_no_lock(weak_table_t *weak_table, id referent_id,
id *referrer_id)
{
//旧的指针
objc_object *referent = (objc_object *)referent_id;
//指向。。的指针
objc_object **referrer = (objc_object **)referrer_id;
weak_entry_t *entry;
//判断
if (!referent) return;
// 判断weak_table是否存在对该对象的weak_entry
//weak_entry_for_referent :返回对象的weak_entry
if ((entry = weak_entry_for_referent(weak_table, referent))) {
//移除该entry中的指针
remove_referrer(entry, referrer);
bool empty = true;
if (entry->out_of_line() && entry->num_refs != 0) {
empty = false;
}
else {
for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
if (entry->inline_referrers[i]) {
empty = false;
break;
}
}
}
//如果该entry为空 则删除之
if (empty) {
weak_entry_remove(weak_table, entry);
}
}
// Do not set *referrer = nil. objc_storeWeak() requires that the
// value not change.
}
- The global weak references table. Stores object ids as keys,
- and weak_entry_t structs as their values.
1 | struct weak_table_t { |
weak_register_no_lock 新的指针:
objc-weak.mm line 3911
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61id
weak_register_no_lock(weak_table_t *weak_table, id referent_id,
id *referrer_id, bool crashIfDeallocating)
{
objc_object *referent = (objc_object *)referent_id;
objc_object **referrer = (objc_object **)referrer_id;
if (!referent || referent->isTaggedPointer()) return referent_id;
//判断被引用的对象存活
// ensure that the referenced object is viable
bool deallocating;
// 是否支持内存管理
if (!referent->ISA()->hasCustomRR()) {
//定义为是否正在销毁
deallocating = referent->rootIsDeallocating();
}
else {
//允许弱引用
BOOL (*allowsWeakReference)(objc_object *, SEL) =
(BOOL(*)(objc_object *, SEL))
object_getMethodImplementation((id)referent,
SEL_allowsWeakReference);
if ((IMP)allowsWeakReference == _objc_msgForward) {
return nil;
}
deallocating =
! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
}
if (deallocating) {
//crashIfDeallocating为true时(篇首有提到),结束进程
if (crashIfDeallocating) {
_objc_fatal("Cannot form weak reference to instance (%p) of "
"class %s. It is possible that this object was "
"over-released, or is in the process of deallocation.",
(void*)referent, object_getClassName((id)referent));
} else {
return nil;
}
}
// now remember it and where it is being stored
weak_entry_t *entry;
// 判断weak_table是否存在对该对象的weak_entry
if ((entry = weak_entry_for_referent(weak_table, referent))) {
//该entry中新增指针
append_referrer(entry, referrer);
}
else {
// 新增该对象的weak_entry
weak_entry_t new_entry(referent, referrer);
weak_grow_maybe(weak_table);
weak_entry_insert(weak_table, &new_entry);
}
// Do not set *referrer. objc_storeWeak() requires that the
// value not change.
return referent_id;
}
对象释放,引用计数为0时 的调用顺序如下:
- objc_release
- dealloc
- _objc_rootDealloc
- object_dispose
- objc_destructInstance
- objc_clear_deallocating
- clearDeallocating
- clearDeallocating_slow
- weak_clear_no_lock
- clearDeallocating_slow
- clearDeallocating
- objc_clear_deallocating
- objc_destructInstance
- object_dispose
- _objc_rootDealloc
- dealloc
1 | //referent_id 要释放的对象 |
看到这里就破案啦,
- SideTables是一个全局的Hash表,里面存放了对象的weak指针和引用计数。里面装的是SideTable。对象的内存地址为key ,weak指针和引用计数为value
- 当有weak指针指向、更改指向对象时,会根据对象的内存地址取出相应的SideTable增加、删除相应的weak指针
- 当对象回收时,会调用
weak_clear_no_lock,在全局的weak_table中取出该对象相应的weak_entry,然后将里面的weak指针记为nil(所以weak不会引起野指针的问题,因为指向对象的内存块回收时,指针也被置为nil了)