iOS:Weak指针原理

大家好,我是OB!今天来聊聊Weak指针!

一、Weak使用

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __strong Animal *strong_animal;
    __weak Animal *weak_animal;
    __unsafe_unretained Animal *unsafe_animal;
    NSLog(@"1111");
    
    {
        Animal *animal = [[Animal alloc]init];
        // strong_animal = animal;
        // weak_animal = animal;
        unsafe_animal = animal;
    }
    NSLog(@"2222 %@",strong_animal);	//2222 <Animal: 0x6000030b8670>
    NSLog(@"2222 %@",weak_animal); 		//2222 (null)
    NSLog(@"2222 %@",unsafe_animal);	//crash
}

如果用__unsafe_unretained,当对象释放后,在访问指针会crash。
如果用__weak,当对象释放后,再访问weak_animal指针为nil

二、Weak原理

我们来看看对象释放时发生了什么?
dealloc

还会发现

void objc_object::sidetable_clearDeallocating() {
    SideTable& table = SideTables()[this];
    table.lock();
    RefcountMap::iterator it = table.refcnts.find(this);
    if (it != table.refcnts.end()) {
        if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
            weak_clear_no_lock(&table.weak_table, (id)this);
        }
        table.refcnts.erase(it);
    }
    table.unlock();
}

	|
	|

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);
    if (entry == nil) {
        return;
    }
    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) {
                *referrer = nil; // 将weak指针变为nil
            }
            else if (*referrer) {
                _objc_inform("__weak variable at %p holds %p instead of %p. "
                             "This is probably incorrect use of "
                             "objc_storeWeak() and objc_loadWeak(). "
                             "Break on objc_weak_error to debug.\n", 
                             referrer, (void*)*referrer, (void*)referent);
                objc_weak_error();
            }
        }
    }
    
    weak_entry_remove(weak_table, entry);
}

里面有几个结构: SideTables,SideTable ,weak_table

1:SideTables

是一个64个元素长度的hash数组,里面存储了SideTable。SideTables的hash键值就是一个对象obj的地址。SideTabls可以通过全局的静态函数获取:SideTable& table = SideTables()[this];

static StripedMap<SideTable>& SideTables() {
    return *reinterpret_cast<StripedMap<SideTable>*>(SideTableBuf);
}

2:SideTable

主要存放了OC对象的引用计数和弱引用相关信息

struct SideTable {
    spinlock_t slock;
    RefcountMap refcnts; //引用计数表
    weak_table_t weak_table; //弱引用表
    SideTable() {
        memset(&weak_table, 0, sizeof(weak_table));
    }
    ~SideTable() {
        _objc_fatal("Do not delete SideTable.");
    }
    //省略其他信息....
};

RefcountMap refcnts

以DisguisedPtr<objc_object>为key的hash表,用来存储OC对象的引用计数(仅在未开启isa优化 或 在isa优化情况下isa_t的引用计数溢出时才会用到)。

weak_table_t weak_table

存储对象弱引用指针的hash表。是OC weak功能实现的核心数据结构。

struct weak_table_t {
    weak_entry_t *weak_entries; // hash数组,用来存储弱引用对象的相关信息weak_entry_t
    size_t    num_entries;// hash数组count
    uintptr_t mask;
    uintptr_t max_hash_displacement;
};

SideTables一共只有64个节点,而在我们的APP中,一般都会不只有64个对象,因此,多个对象一定会重用同一个SideTable节点,也就是说,一个weak_table会存储多个对象的弱引用信息。因此在一个SideTable中,又会通过weak_table作为hash表再次分散存储每一个对象的弱引用信息。

 weak_entry_t *weak_entries;

这是一个hash数组。通过对象的地址,算出hash值,对应到具体的桶,每个桶里面放的是一个weak指针的数组。清除的时候就是遍历里面的的weak指针,全部置为nil;

void weak_clear_no_lock(weak_table_t *weak_table, id referent_id) {
// .....
   for (size_t i = 0; i < count; ++i) {
        objc_object **referrer = referrers[i];
        if (referrer) {
            if (*referrer == referent) {
                *referrer = nil; // 将weak指针变为nil
            }
            // .....
        }
    }
}

总结构大致如下
img

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值