简体   繁体   English

为什么弱强舞蹈能够保持循环?

[英]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. blkstr是财产。

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 selfweakSelf and strongSelf point to the same object, the different of them is just strong or weak. 结论是selfweakSelf selfstrongSelf self指向同一个对象,它们的不同只是强弱。 In my opinion, self and strongSelf is identical. 在我看来, selfstrongSelf是完全相同的。 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. 我想你误解了一些问题。

  • Block doesn't keep strong reference of self , it keeps a weak reference. Block没有强烈的self参考,它保留了一个弱的参考。
  • self and strongSelf isn't identical. selfstrongSelf self并不完全相同。
  • strongSelf is strong reference of weakSelf not self so it won't cause retain cycle. strongSelf是很强的借鉴weakSelf没有self ,这样就不会引起保留周期。
  • If 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM