ios - weak variable with a strong reference in a block: does not create a retain cycle? -
why work when pass weak reference strong reference inside block? if local variable in block retained, should add retain self
, create bad retain cycle?
here example :
__weak id weakself = self; [self.operationqueue addoperationwithblock:^{ nsnumber* result = findlargestmersenneprime(); [[nsoperationqueue mainqueue] addoperationwithblock:^{ myclass* strongself = weakself; strongself.textlabel.text = [result stringvalue]; }]; }];
when create or copy block (it copied when you, example, schedule gcd), referenced variables captured (unless declared __block specifier). strong references retained, weak references not.
when create local strongself
variable keeps self
alive while block executes (i.e. while it's not executed , sits in property there's no strong reference). when reference self
directly - self
captured , retained, keeps self
while block alive.
__weak id weakself = self; [self.operationqueue addoperationwithblock:^{ nsnumber* result = findlargestmersenneprime(); [[nsoperationqueue mainqueue] addoperationwithblock:^{ myclass* strongself = weakself; // strong reference when block executes [self foo]; // strong reference when block created/copied strongself.textlabel.text = [result stringvalue]; }]; }];
see difference? if kill strong pointers object direct self
reference there still 1 strong reference inside block, 1 captured , retained. @ same time local strongself
pointer holds strong reference self
while block executed, so, if self
dead, weakself
nil , strongself
nil value.
Comments
Post a Comment