[英]Why could weak-strong dance break retain cycle?
This is my code: 这是我的代码:
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
and str
is property. blk
和str
是财产。
and I got the log like this: 我得到了这样的日志:
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
The conclusion is self
、 weakSelf
and strongSelf
point to the same object, the different of them is just strong or weak. 结论是
self
, weakSelf
self
和strongSelf
self
指向同一个对象,它们的不同只是强弱。 In my opinion, self
and strongSelf
is identical. 在我看来,
self
和strongSelf
是完全相同的。 so I think the memory of this code like this: 所以我认为这段代码的内存是这样的:
My confusion is when block is executed, block will strong reference self, but if self is not dealloced in the same time, self also strong reference block. 我的困惑是当块执行时,block会强引用self,但如果self在同一时间没有被释放,self也会强引用块。 Will it cause retain cycle?
它会导致保留周期吗?
In my opinion, it won't cause retain cycle. 在我看来,它不会导致保留周期。 I think you misunderstand some points.
我想你误解了一些问题。
self
, it keeps a weak reference. self
参考,它保留了一个弱的参考。 self
and strongSelf
isn't identical. self
和strongSelf
self
并不完全相同。 strongSelf
is strong reference of weakSelf
not self
so it won't cause retain cycle. strongSelf
是很强的借鉴weakSelf
没有self
,这样就不会引起保留周期。 self
is not deallocated when block executed, strongSelf
will be a strong reference of self
. self
未被释放,则strongSelf
将成为self
的强引用。 But strongSelf
is a local variable ,it only makes self can't be deallocated until block executed completely. strongSelf
是一个局部变量,它只能让自己在块完全执行之前不能被释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.