__block 和__weak 区别及使用
2016-06-20 14:51
363 查看
API Reference对__block变量修饰符有如下几处解释:
大概意思归结出来就是两点:
1.__block对象在block中是可以被修改、重新赋值的。
2.__block对象在block中不会被block强引用一次,从而不会出现循环引用问题。
API Reference对__weak变量修饰符有如下几处解释:
使用了__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。所以尽可能不要使用这个修饰符。
//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。所以尽可能不要使用这个修饰符。
相关文章推荐
- 使用gulp-uncss清理多余无用css
- 如何提高码农产量,基于ASP.NET MVC的敏捷开发框架之工作流开发随笔三
- 【hibernate】 hibernate的主键策略
- 为什么学习go语言编程?
- 第十一周上机实践-点圆圆柱族类设计(补)
- PHP设计模式
- 运维学习和发展的一个线路
- appscan漏洞--目录列表
- 源码下载网址
- SVN e155004 locked
- extmail日常维护
- Win7 ie浏览器总是停止工作的解决办法 四种win7ie浏览器停止工作
- Java 动态编译
- 签订二手房买卖合同时应注意的7个细节
- Android studio 异常 libpng warning: iCCP: Not recognizing known sRGB profile that has be
- 用poi的XSLF创建ppt,添加文本的时候多了空行
- springmvc validator验证的使用
- linux下mysql命令大全
- Espresso 测试SwipeRefreshLayout 组件,下拉问题记录
- 企业该如何正确选择即时通讯软件