[英]Why does the weak/strong dance solve this strong reference cycle? I don't understand
[英]Why could weak-strong dance break retain cycle?
这是我的代码:
NSLog(@"%p",self);
__weak typeof(self) weakSelf = self;
NSLog(@"%p", weakSelf);
[self setBlk:^{
__strong typeof(weakSelf) strongSelf = weakSelf;
NSLog(@"%p", strongSelf);
strongSelf.str = @"foo";
}];
self.blk();
blk
和str
是财产。
我得到了这样的日志:
2018-04-03 14:51:57.151946+0800 Block[20267:148833] 0x7fafa1506d90
2018-04-03 14:51:57.152177+0800 Block[20267:148833] 0x7fafa1506d90
2018-04-03 14:51:57.152359+0800 Block[20267:148833] 0x7fafa1506d90
结论是self
, weakSelf
self
和strongSelf
self
指向同一个对象,它们的不同只是强弱。 在我看来, self
和strongSelf
是完全相同的。 所以我认为这段代码的内存是这样的:
我的困惑是当块执行时,block会强引用self,但如果self在同一时间没有被释放,self也会强引用块。 它会导致保留周期吗?
在我看来,它不会导致保留周期。 我想你误解了一些问题。
self
参考,它保留了一个弱的参考。 self
和strongSelf
self
并不完全相同。 strongSelf
是很强的借鉴weakSelf
没有self
,这样就不会引起保留周期。 self
未被释放,则strongSelf
将成为self
的强引用。 但是strongSelf
是一个局部变量,它只能让自己在块完全执行之前不能被释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.