__weak与__block修饰符到底有什么区别
2015-05-04 09:47
337 查看
API Reference对__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不可以。
4.__block对象在ARC下可能会导致循环引用,非ARC下会避免循环引用,__weak只在ARC下使用,可以避免循环引用。
更多关于__block变量的详细解释,参见我的另一篇文章,详细探讨了__block的实现原理
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.
大概意思归结出来就是:
__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不可以。
4.__block对象在ARC下可能会导致循环引用,非ARC下会避免循环引用,__weak只在ARC下使用,可以避免循环引用。
更多关于__block变量的详细解释,参见我的另一篇文章,详细探讨了__block的实现原理
PS:__unsafe_unretained修饰符可以被视为iOS SDK 4.3以前版本的__weak的替代品,不过不会被自动置空为nil。所以尽可能不要使用这个修饰符。
相关文章推荐
- __weak与__block修饰符到底有什么区别
- __weak与__block修饰符到底有什么区别
- __weak与__block修饰符到底有什么区别
- __weak与__block修饰符到底有什么区别
- __weak与__block修饰符到底有什么区别
- __weak与__block修饰符到底有什么区别 + 属性的特性简介
- __weak与__block修饰符到底有什么区别
- iOS __weak与__block修饰符到底有什么区别
- IOS开发 __weak与__block修饰符到底有什么区别
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
- 从数据备份恢复来看,iCloud和iTunes到底有什么区别?
- mvc和三层架构到底有什么区别
- 免费在线客服系统和付费的到底有什么区别?
- 四个修饰符到底有什么区别?
- 基于JDK动态代理和CGLIB动态代理到底有什么区别?
- mvc和三层架构到底有什么区别
- HTTPS和HTTP有什么区别,到底安全在哪里?
- c,c++,vc++,c++buider到底有什么区别和联系
- 20万、50万、100万的算法工程师,到底有什么区别?
- JavaScript的toString()和valueOf()区别到底是什么