1、weak是弱引用,所引用的对象计数不会加1。

2、weak变量在其引用的对象被销毁之后,会被置为nil。

3、weak通常用于block, delegate, NSTimer,以解决循环引用带来的内存泄漏问题。

NSObject *obj = [[NSObject alloc] init]; // obj是被引用对象的指针
id __weak obj1 = obj; // obj1是weak变量,也是被引用对象的指针

weak的底层实现,简化的源码及解析如下:

id objc_storeWeak(id *location, id newObj) // objc_storeWeak(&obj1, obj)
{
id oldObj;
SideTable *oldTable;
SideTable *newTable; oldObj = *location; // weak变量,也是被引用对象的指针
// 根据被引用对象的指针的哈希值得到对应的SideTable
oldTable = SideTable::tableForPointer(oldObj);
newTable = SideTable::tableForPointer(newObj); if (oldObj) {
weak_unregister_no_lock(&oldTable->weak_table, oldObj, location); // 删掉旧引用,因为location要指向newObj,其实应该先判断oldObj != newObj的
}
if (newObj) {
newObj = weak_register_no_lock(&newTable->weak_table, newObj,location); // 添加新引用
}
*location = newObj; return newObj;
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 ((entry = weak_entry_for_referent(weak_table, referent))) {
remove_referrer(entry, referrer); // 删掉旧的weak变量的指针
bool empty = true;
for (size_t i = 0; i < WEAK_INLINE_COUNT; i++) {
if (entry->inline_referrers[i]) {
empty = false;
break;
}
}
if (empty) {
weak_entry_remove(weak_table, entry); // 如果旧的被引用对象的指针对应的weak变量的指针数组空了,则删掉这个被引用对象的指针
}
}
}

  

id weak_register_no_lock(weak_table_t *weak_table, id referent_id, id *referrer_id)
{
// 被引用对象的指针
objc_object *referent = (objc_object *)referent_id;
// weak变量的指针
objc_object **referrer = (objc_object **)referrer_id; weak_entry_t *entry;
if ((entry = weak_entry_for_referent(weak_table, referent))) {
append_referrer(entry, referrer); // 有就往指针数组加一个
} else {
weak_entry_t new_entry;
new_entry.referent = referent;
new_entry.inline_referrers[0] = referrer;
for (size_t i = 1; i < WEAK_INLINE_COUNT; i++) {
new_entry.inline_referrers[i] = nil;
}
weak_grow_maybe(weak_table);
weak_entry_insert(weak_table, &new_entry); // 没有就创建一个指针数组,然后加一个
} return referent_id;
}
class SideTable {
private:
static uint8_t table_buf[SIDE_TABLE_STRIPE * SIDE_TABLE_SIZE]; // 所有SideTable对象共用,数组元素是SideTable *。看成全局数组,而不属于某个SideTable对象,更好理解。 public:
weak_table_t weak_table; // SideTable对象和weak表一一对应 static SideTable *tableForPointer(const void *p)
{
uintptr_t a = (uintptr_t)p;
int index = ((a >> 4) ^ (a >> 9)) & (SIDE_TABLE_STRIPE - 1);
return (SideTable *)&table_buf[index * SIDE_TABLE_SIZE];
} };
// weak表
struct weak_table_t {
weak_entry_t *weak_entries;
};
// weak表项
struct weak_entry_t {
DisguisedPtr<objc_object> referent; // 被引用对象的指针
weak_referrer_t inline_referrers[WEAK_INLINE_COUNT]; // weak变量的指针数组
};

来个直观的整体结构图如下:

参考链接:

https://opensource.apple.com/source/objc4/objc4-532/runtime/NSObject.mm.auto.html

https://opensource.apple.com/source/objc4/objc4-646/runtime/objc-weak.h

Objective-C weak深入理解的更多相关文章

  1. strong & weak 的理解

    import "ViewController.h" @interface ViewController () /*weak*/ @property (nonatomic,weak) ...

  2. [翻译]Understanding Weak References(理解弱引用)

    原文 Understanding Weak References Posted by enicholas on May 4, 2006 at 5:06 PM PDT 译文 我面试的这几个人怎么这么渣啊 ...

  3. iOS深入学习之Weak关键字介绍

    iOS深入学习之Weak关键字介绍 前言 从大二的开始接触OC就用到了weak属性修饰词,但是当时只是知道如何去用这个关键字:防止循环引用.根本没有深入地去了解它. 在刚来北京的时候面试过程中也常常考 ...

  4. IOS开发基础知识--碎片48

    1:Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:  static NSString *CellIdentif ...

  5. [UWP] 对应用进行A/B测试

    [对A/B测试的看法] 开发者在Dev Center中设置几种应用变体,这几种变体有几个变量的值不一样,比如有变体A和变体B(当然还可以加上变体C,Dev Center最多支持5个变体),A和B的不同 ...

  6. C --> OC with RunTime

    前言 本来打算写一篇关于runtime的学习总结,无奈长篇大论不是我的风格,就像写申论一样痛苦,加之网上关于tuntime的文章多如牛毛,应该也够童子们学习的了,今天就随便聊聊我的理解吧. runti ...

  7. Xcode 7.3 cannot create __weak reference in file using manual reference counting

      原帖地址 http://stackoverflow.com/questions/36147625/xcode-7-3-cannot-create-weak-reference-in-file-us ...

  8. 更新mac系统和更新到Xcode7.3版本出现的: cannot create __weak reference in file using manual reference counting

    之前的编程没有遇到过,应该是苹果官方那边又做了新规吧. 不过不要紧,只要根据这个就能解决报错问题.  Set Build Settings -> Apple LLVM 7.1 - Languag ...

  9. Automake

    Automake是用来根据Makefile.am生成Makefile.in的工具 标准Makefile目标 'make all' Build programs, libraries, document ...

随机推荐

  1. opencv学习系列:连通域参考处理

    OpenCV里提取目标轮廓的函数是findContours,它的输入图像是一幅二值图像,输出的是每一个连通区域的轮廓点的集合:vector<vector<Point>>. 外层 ...

  2. Python shelve

    shelve模块只有一个open函数,返回类似字典的对象,可读可写; key必须为字符串,而值可以是python所支持的数据类型. import shelve f = shelve.open('SHE ...

  3. JS之用ES6 Promise解决回调地狱(这里以小程序为例)

    首先 写一个请求的方法,如: /** * 银行窗口 * 你需要给我提供相关的相关参数我帮你提交到服务器上 * 我会给你一个等待区的编号给你 你去等待区等待,我处理完成会去等待区通知你 * @param ...

  4. 2017-10-10 都市传说: "部分"中文出现乱码

    知乎原链, 作者亦本人 事情起源于项目另一开发者在中文Windows下构建时遇到的部分中文出现乱码问题. 当时很不解的是, 为什么会只有部分出现乱码. 第一感觉是, 如果编码转换不正确, 要么全乱码, ...

  5. 可视化接口管理工具RAP,模拟数据,校验接口

    最近看到一个不错的接口管理的工具,分享一下 RAP ppt介绍:http://www.imooc.com/video/11060 RAP是一个可视化接口管理工具 通过分析接口结构,动态生成模拟数据,校 ...

  6. 惊闻企业Web应用生成平台 活字格 V4.0 免费了,不单可视化设计器免费,服务器也免费!

    官网消息: 针对活字格开发者,新版本完全免费!您可下载活字格 Web 应用生成平台 V4.0 Updated 1,方便的创建各类 Web 应用系统,任意部署,永不过期. 我之前学习过活字格,也曾经向用 ...

  7. loadrunner 运行场景-Controller及Load Generators宿主主机优化

    运行场景-Controller及Load Generators宿主主机优化 by:授客 QQ:1033553122 1.  Load Generator宿主主机优化设置 win7以下:进入“控制面板” ...

  8. wap2app(六)-- wap2app的原生标题头无法隐藏

    大概有一个星期没有用HBuilder打包,今天更新了HBuilder版本再继续打包,就出现了一系列问题.其中有一个就是打包之后,除首页外,其他页面多出了原生标题,如下图: 查阅资料,打开 sitema ...

  9. Python中DataFrame去重

    # 去除重复行数据 keep:'first':保留重复行的第一行,'last':保留重复行的最后一行,False:删除所有重复行df = df.drop_duplicates( subset=['YJ ...

  10. Spring Boot 中配置文件application.properties使用

    一.配置文档配置项的调用(application.properties可放在resources,或者resources下的config文件夹里) package com.my.study.contro ...