iOS底层学习16 -- block循环引用问题
2020-09-01 本文已影响0人
恋空K








_weak:不会产生强引用
_unsafe_unretained:不会产生强引用,不安全
如果是_weak修饰,当指向的对象销毁了,会自动把保存的地址值置为nil,而_unsafe_unretained修饰,指向的对象就算销毁了,也不会把保存的地址置为nil的。




//MRC是不支持_weak的

__weak typeof(self) weakSelf = self;
self.someBlock = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
[self doSomething];
}
在block外部使用weakSelf定义self的弱引用对象,然后在block内部对weakSelf进行一次强引用(防止执行到block块中代码的时候self被提前释放导致weakSelf为nil),由于strongSelf定义为局部变量,当其作用域结束后,strongSelf自动释放对self的强引用,从而避免了retain cycle。






