__block 和__weak 区别及使用
2024-08-31 12:22:10
API Reference对__block变量修饰符有如下几处解释:
//A powerful feature of blocks is that they can modify
variables in the same lexical scope. You signal that a block
can modify a variable using the __block storage type
modifier.
//At function level are __block variables. These are mutable
within the block (and the enclosing scope) and are preserved
if any referencing block is copied to the heap.
大概意思归结出来就是两点:
1.__block对象在block中是可以被修改、重新赋值的。
2.__block对象在block中不会被block强引用一次,从而不会出现循环引用问题。
API Reference对__weak变量修饰符有如下几处解释:
__weak specifies a reference that does not keep the
referenced object alive. A weak reference is set to nil when
there are no strong references to the object.
使用了__weak修饰符的对象,作用等同于定义为weak的property。自然不会导致循环引用问题,因为苹果文档已经说的很清楚,当原对象没有任何强引用的时候,弱引用指针也会被设置为nil。
因此,__block和__weak修饰符的区别其实是挺明显的:
1.__block不管是ARC还是MRC模式下都可以使用,可以修饰对象,还可以修饰基本数据类型。
2.__weak只能在ARC模式下使用,也只能修饰对象(NSString),不能修饰基本数据类型(int)。
3.__block对象可以在block中被重新赋值,__weak不可以。
PS:__unsafe_unretained修饰符可以被视为iOS SDK 4.3以前版本的__weak的替代品,不过不会被自动置空为nil。所以尽可能不要使用这个修饰符。
最新文章
- 分布式锁1 Java常用技术方案
- MVC 自定义Htmlhelper扩展
- VC----Class Style类风格和窗口风格
- Java API 实现HBase的数据添加与过滤查询
- 解决:CWnd::SetWindowText报Assertion failure
- jsoup web scraping
- 深入浅出Node.js (6) - 理解Buffer
- 简便数据库——ORMLite框架
- Ubuntu12.04 LTS Add Sources List
- EasyUI DataGrid 中字段 formatter 格式化不起作用
- 每天一个Linux命令(12)--more命令
- 精读《Scheduling in React》
- jarvisoj level5爬坑
- 记录一则xtts测试遇到的诡异现象
- 1094. The Largest Generation (25)-(dfs,树的遍历,统计每层的节点数)
- Linux内核设计(第一周)——从汇编语言出发理解计算机工作原理
- 在Android平台下搭建PhoneGap开发环境--用HTML5开发游戏
- 第89天:HTML5中 访问历史、全屏和网页存储API
- (Oracle)自定义调用AWR&;ADDM
- Struts2+Datagrid表格显示(可显示多表内容)
热门文章
- Codeforces 538 C. Tourist's Notes
- Web CI过程中的Security解决方案
- BSGS与二次剩余
- 洛谷 P1452 Beauty Contest
- Problem M: 第几天——C语言初学者百题大战之十八
- catalina_home与catalina_base
- jvm-监控指令-jstack
- javascript设定指定元素的父结点的孙子节点的属性
- projecteuler----&;gt;problem=11----Largest product in a grid
- java的poi技术读取Excel[2003-2007,2010]