![](/img/trans.png)
[英]How to keep a strong reference inside of a block without having a retain cycle
[英]weak variable with a strong reference in a block: does not create a retain cycle?
当我们将弱引用传递给块内部的强引用时,为什么它起作用? 如果保留了块中的局部变量,是否应该向self
添加一个保留,从而造成这个不良的保留周期?
这是示例:
__weak id weakSelf = self;
[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
MyClass* strongSelf = weakSelf;
strongSelf.textLabel.text = [result stringValue];
}];
}];
创建或复制一个块时(例如,在将其调度到gcd时可以复制它),将捕获引用的变量(除非使用__block指定符声明)。 保留强引用,弱引用不保留。
当您创建局部strongSelf
变量时,它会在执行块时使self
保持活动状态(即,不执行且位于属性中的对象没有强引用)。 当您引用self
直接- self
被捕获并保留下来,现在它保持self
,而块是活的 。
__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];
}];
}];
看到不同? 如果您使用直接self
引用杀死所有指向对象的强指针,则在块内仍然存在一个强引用,该强引用被捕获并保留。 同时,本地strongSelf
指针仅在执行块时持有对self
强引用,因此,如果self
已死,则weakSelf
将为nil, strongSelf
将获得nil值。
不,这不会产生循环,因为自我没有被捕捉为强者! :)
strongSelf是一个强引用,可保留self BUT,因为strongSelf是本地var,在完成块时释放它,并且保留计数下降
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.