博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS __block和__weak的区别
阅读量:4066 次
发布时间:2019-05-25

本文共 1062 字,大约阅读时间需要 3 分钟。

//联系人:石虎  QQ: 1224614774昵称:嗡嘛呢叭咪哄

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。所以尽可能不要使用这个修饰符

谢谢!!!

转载地址:http://bptji.baihongyu.com/

你可能感兴趣的文章
spring 事务
查看>>
Linux web工程部署远程必备软件安装
查看>>
Windows 7下硬盘安装CentOS6.4的解决方法
查看>>
JSP不支持EL表达式的解决方案
查看>>
Struts2类型转换器
查看>>
struts2 使用注解、反射、拦截器实现基于方法的权限控制
查看>>
maven 架设 struts2 注解方式 权限控制
查看>>
struts2之多个文件上传
查看>>
struts2之单个文件上传
查看>>
struts2自定义拦截器 模拟session超时的处理
查看>>
面试技巧
查看>>
struts2之防止表单重复提交
查看>>
人不成熟的几大特征
查看>>
《礼仪73》、《处事22计》、《心态24条》、《伤心50句》、《学会长大20》
查看>>
人人都会变老
查看>>
oracle connect by用法
查看>>
Oracle 树操作(select…start with…connect by…prior)
查看>>
maven struts2中,使用ModelDriven
查看>>
通过web.xml传递初始参数
查看>>
过滤器与拦截器
查看>>