Reputation: 123
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 self
、weakSelf
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?
Upvotes: 1
Views: 690
Reputation: 12144
In my opinion, it won't cause retain cycle. I think you misunderstand some points.
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.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. Upvotes: 3