简体   繁体   中英

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.

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. In my opinion, self and strongSelf is identical. 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. 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.
  • self and strongSelf isn't identical.
  • strongSelf is strong reference of weakSelf not self so it won't cause retain cycle.
  • If self is not deallocated when block executed, strongSelf will be a strong reference of self . But strongSelf is a local variable ,it only makes self can't be deallocated until block executed completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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