Skip to content

Commit 6852c4e

Browse files
committed
update [8. runtime 如何实现 weak 属性]
增加runtime源码示例,以及源码链接。
1 parent cd5b9a7 commit 6852c4e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

01《招聘一个靠谱的iOS》面试题参考答案/《招聘一个靠谱的iOS》面试题参考答案(上).md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,51 @@ typedef struct {
771771
772772
(注:在下文的《使用runtime Associate方法关联的对象,需要在主对象dealloc的时候释放么?》里给出的“对象的内存销毁时间表”也提到`__weak`引用的解除时间。)
773773

774+
775+
先看下 runtime 里源码的实现:
776+
777+
778+
```Objective-C
779+
/**
780+
* The internal structure stored in the weak references table.
781+
* It maintains and stores
782+
* a hash set of weak references pointing to an object.
783+
* If out_of_line==0, the set is instead a small inline array.
784+
*/
785+
#define WEAK_INLINE_COUNT 4
786+
struct weak_entry_t {
787+
DisguisedPtr<objc_object> referent;
788+
union {
789+
struct {
790+
weak_referrer_t *referrers;
791+
uintptr_t out_of_line : 1;
792+
uintptr_t num_refs : PTR_MINUS_1;
793+
uintptr_t mask;
794+
uintptr_t max_hash_displacement;
795+
};
796+
struct {
797+
// out_of_line=0 is LSB of one of these (don't care which)
798+
weak_referrer_t inline_referrers[WEAK_INLINE_COUNT];
799+
};
800+
};
801+
};
802+
803+
/**
804+
* The global weak references table. Stores object ids as keys,
805+
* and weak_entry_t structs as their values.
806+
*/
807+
struct weak_table_t {
808+
weak_entry_t *weak_entries;
809+
size_t num_entries;
810+
uintptr_t mask;
811+
uintptr_t max_hash_displacement;
812+
};
813+
```
814+
815+
具体完整实现参照 [objc/objc-weak.h](https://opensource.apple.com/source/objc4/objc4-646/runtime/objc-weak.h)
816+
817+
818+
774819
我们可以设计一个函数(伪代码)来表示上述机制:
775820

776821
`objc_storeWeak(&a, b)`函数:

0 commit comments

Comments
 (0)