iOSInterviewQuestions icon indicating copy to clipboard operation
iOSInterviewQuestions copied to clipboard

建议增加一个问题:__block和__weak的区别

Open liuxuan30 opened this issue 9 years ago • 8 comments

建议增加一个问题:__block和__weak的区别。问题很简单,但是必须知道的。

liuxuan30 avatar Aug 18 '15 02:08 liuxuan30

@ChenYilong 求解~

sauchye avatar Aug 24 '15 15:08 sauchye

估计他说的是解决block循环引用在arc与mrc的不同实现

lzkkk avatar Sep 16 '15 00:09 lzkkk

@lzkkk 没这么复杂。。。 参考http://www.bubuko.com/infodetail-782508.html 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。所以尽可能不要使用这个修饰符。

liuxuan30 avatar Sep 16 '15 01:09 liuxuan30

你确定使用__block在arc中可以直接解决block()循环引用.好像还得在block中使用完强制置为nil 并且保证block()被调用.使用__weak 或者局部__strong对象好一点

lzkkk avatar Sep 17 '15 06:09 lzkkk

你确定使用__block在arc中可以直接解决block()循环引用.好像还得在block中使用完强制置为nil 并且保证block()被调用.使用__weak 或者局部__strong对象好一点

lzkkk avatar Sep 17 '15 06:09 lzkkk

不是一类东西,没有可比性

amisare avatar Aug 18 '17 09:08 amisare

MyTestProject.zip 测试__block 解决循环引用的问题

wangjianlewo avatar Sep 29 '17 07:09 wangjianlewo

__block一般是用来修饰非对象的基本数据类型的,作用是修改block捕获变量的方式,由值传递改变为指针传递。被__block修饰的变量,可以在block中修改。

而__weak是改变对象的内存管理策略,一般是修饰OC对象类型的。在ARC机制下,默认是使用__strong修饰符修饰的,也就是说赋值时会对对象进行一次强引用,而用__weak修饰的对象,在赋值时不会强引用,而是弱引用

CoulsonWang avatar Sep 29 '17 07:09 CoulsonWang