iOS __weak的底层实现

1.为什么要使用weak关键字修饰对象

因为使用weak修饰的对象在对象释放的时候,引用它的指针会自动被置为nil;

2. weak和__unsafe_unretained差别,是不是__unsafe_unretained因为weak出现而不再使用了

__unsafe_unretained和weak区别在于,所引用的对象在释放的时候,引用它的指针会不会自动被置为nil,可能会产生野指针,但这并不代表__unsafe_unretained就没用了,在一些情况下合理使用__unsafe_unretained能够带来一定性能上的提升.

3.weak的底层的实现
iOS __weak的底层实现_第1张图片
weak存储.png

参照代码:
SideTable

struct SideTable {
    weak_table_t weak_table;
    ....
};

weak_table

struct weak_table_t {
    weak_entry_t *weak_entries;
};

weak_entry_t

struct weak_entry_t {
    DisguisedPtr referent;
    union {
        struct {
            weak_referrer_t *referrers;
        };
    };
 ...
};

可以得到一个结论,系统为我们创建了一个全局的weak_table,这个表里面有一个weak_entries这样的一个一维数组,重点关注这个weak_entries这个数组中的每个结构体weak_entry_t,其中referent为被弱引用的对象, 而referrers则是指向这个弱引用的的地址,举个例子

@interface Dog : NSObject
@property (nonatomic,weak) NSObject *referent;
@end
// 暂时可认为这个referent和weak_entry_t结构体中的referent是一致的,而referrers[0] = & referent;(ps.假设目前就一个弱指针指向referent)
4.weak修饰对象的存储

4.1 property中使用weak修饰

@property (nonatomic,weak) NSObject *referent;

// 底层实现函数入口
id objc_storeWeak(id *location, id newObj)
{
    return storeWeak
        (location, (objc_object *)newObj);
}

4.2 使用__weak修饰对象

__weak NSObject *referent

// 底层实现函数入口
id objc_initWeak(id *location, id newObj)
{
    if (!newObj) {
        *location = nil;
        return nil;
    }

    return storeWeak
        (location, (objc_object*)newObj);
}

其实不论是使用weak还是__weak底层都是调用storeWeak这个函数,区别在于模板的第一个参数HaveOld,官方解释如下

If HaveOld is true, the variable has an existing value 
that needs to be cleaned up. This value might be nil.

进入到storeWeak函数中

static id storeWeak(id *location, objc_object *newObj)
{
...
    if (haveNew) {
        newObj = (objc_object *)
            weak_register_no_lock(&newTable->weak_table, (id)newObj, location, 
                                  crashIfDeallocating);
        // Do not set *location anywhere else. That would introduce a race.
        *location = (id)newObj;
    }
...
}

关注weak_register_no_lock函数

id 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;

    // now remember it and where it is being stored
    weak_entry_t *entry;
    if ((entry = weak_entry_for_referent(weak_table, referent))) {
        append_referrer(entry, referrer);
    } 
    else {
        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;
}

优先检查weak_table中是否存在referent作为key的的weak_entry_t,如果存在,则插入一个新的指向这个弱引用对象的referrer地址,对应的关系如下图:

iOS __weak的底层实现_第2张图片
unit_weak_entry.png

先看看在没有 weak_entry_t存储了 referent的时候如何处理,代码如下

weak_entry_t new_entry(referent, referrer);
weak_grow_maybe(weak_table);
weak_entry_insert(weak_table, &new_entry);

先为这个referent创建了一个weak_entry_t,目前也就一个referrer弱引用referent,接下来判定weak_table的存储空间是否足够

static void weak_grow_maybe(weak_table_t *weak_table)
{
    size_t old_size = TABLE_SIZE(weak_table);

    // Grow if at least 3/4 full.
    if (weak_table->num_entries >= old_size * 3 / 4) {
        weak_resize(weak_table, old_size ? old_size*2 : 64);
    }
}

static void weak_resize(weak_table_t *weak_table, size_t new_size)
{
    size_t old_size = TABLE_SIZE(weak_table);
    
    weak_entry_t *old_entries = weak_table->weak_entries;
    weak_entry_t *new_entries = (weak_entry_t *)
        calloc(new_size, sizeof(weak_entry_t));
   // 因为mask为2^n,所以-1,是的mask等于全1的二进制
    weak_table->mask = new_size - 1;
    weak_table->weak_entries = new_entries;
    weak_table->max_hash_displacement = 0;
    weak_table->num_entries = 0;  // restored by weak_entry_insert below
    
   // 重新将老的数据插入到插入到新分配的空间中
    if (old_entries) {
        weak_entry_t *entry;
        weak_entry_t *end = old_entries + old_size;
        for (entry = old_entries; entry < end; entry++) {
            if (entry->referent) {
                weak_entry_insert(weak_table, entry);
            }
        }
        free(old_entries);
    }
}

weak_tablenum_entries大于总量的3/4,其中这个总量存储在weak_tablemask字段中,初始使用64,以后每次扩容为上次大小的2倍.
接下来插入这个新的weak_entry_t

static void weak_entry_insert(weak_table_t *weak_table, weak_entry_t *new_entry)
{
    weak_entry_t *weak_entries = weak_table->weak_entries;
    assert(weak_entries != nil);
   // 
    size_t begin = hash_pointer(new_entry->referent) & (weak_table->mask);
    size_t index = begin;
    size_t hash_displacement = 0;
    while (weak_entries[index].referent != nil) {
        index = (index+1) & weak_table->mask;
        if (index == begin) bad_weak_table(weak_entries);
        hash_displacement++;
    }
    
   // 这个index即为弱引用对象的地址,hash偏移后产生的
    weak_entries[index] = *new_entry;
    weak_table->num_entries++;

    if (hash_displacement > weak_table->max_hash_displacement) {
        weak_table->max_hash_displacement = hash_displacement;
    }
}

weak_entry_insert的算法算是__weak实现的精华所在,如果直接使用弱引用对象的地址作为index,那么weak_entries的大小就要alloc对应系统位数的内存大小,显然不可能,这样内存空间将会全部被占用.因此出现了上面这个方法,根据存储对象的数量,动态申请内存,再根据引用对象的地址mask后,一定是小于TABLE_SIZE,但是可能有两个不同的对象,结尾的地址是相同的,这个时候就需要特殊处理,每次index++,直到这个index对应的位置没有被使用.

5.weak修饰对象的释放

当使用weak修饰的对象被释放,调用流程如下图所示

iOS __weak的底层实现_第3张图片
被弱引用对象的释放.png

从图可以看出 referent对象在释放以后,会去判定是否在weak表中有数据,如果存在会利用 weak_clear_no_lock函数,将referrers全部置为nil,代码如下

void 
weak_clear_no_lock(weak_table_t *weak_table, id referent_id) 
{
    objc_object *referent = (objc_object *)referent_id;

    weak_entry_t *entry = weak_entry_for_referent(weak_table, referent);

    // zero out references
    weak_referrer_t *referrers;
    size_t count;
    
    if (entry->out_of_line()) {
        referrers = entry->referrers;
        count = TABLE_SIZE(entry);
    } 
    else {
        referrers = entry->inline_referrers;
        count = WEAK_INLINE_COUNT;
    }
    
    for (size_t i = 0; i < count; ++i) {
        objc_object **referrer = referrers[i];
        if (referrer) {
            if (*referrer == referent) {
             // 这是为什么使用weak修饰属性,在释放的时候会被置为nil的原因
                *referrer = nil;
            }
        }
    }
    // 从weak_table中移除这个entry
    weak_entry_remove(weak_table, entry);
}

当某个对象拥有weak属性,在这个对象被释放的时候,会调用下面这个方法,将引用地址置为nil

void objc_destroyWeak(id *location)
{
    (void)storeWeak
        (location, nil);
}

static id 
storeWeak(id *location, objc_object *newObj)
{
    // Clean up old value, if any.
    if (haveOld) {
        weak_unregister_no_lock(&oldTable->weak_table, oldObj, location);
    }
}

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;

    if ((entry = weak_entry_for_referent(weak_table, referent))) {
       // 移除弱引用
        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);
        }
    }
}

static void remove_referrer(weak_entry_t *entry, objc_object **old_referrer)
{
    if (! entry->out_of_line()) {
        for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
            if (entry->inline_referrers[i] == old_referrer) {
                entry->inline_referrers[i] = nil;
                return;
            }
        }
    }

    size_t begin = w_hash_pointer(old_referrer) & (entry->mask);
    size_t index = begin;
    size_t hash_displacement = 0;
    while (entry->referrers[index] != old_referrer) {
        index = (index+1) & entry->mask;
        if (index == begin) bad_weak_table(entry);
        hash_displacement++;
    }
    entry->referrers[index] = nil;
    entry->num_refs--;
}

你可能感兴趣的:(iOS __weak的底层实现)