博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
代码块block :capturing self strongly in this block is
阅读量:6495 次
发布时间:2019-06-24

本文共 2029 字,大约阅读时间需要 6 分钟。

  hot3.png

在代码块中使用对象的成员时(成员变量是属性strong,MRC估计是retain时效果一样,使用方法时也一样):

警告:

意思应该是block会retain一次,所以使用前最好 __block MyClass* bObject = self;

from:

I get the mentioned warning in my code and I'm wondering if this a possibly issue in my case:

ARC enabled.
The warning "Capturing 'self' strongly in this block is likely to lead to a retain cycle" is issued in this method:
- (void) foo
{
    [self.operationQueue addOperationWithBlock:^{
        [self bar];
    }];
}
property operationQueue is declared 'strong'.
I understand the message, that is:
'self' is strongly retaining _operationQueue which itself strongly retains a block which itself strongly retains 'self'.
However, is this a problem in this case? I expect message bar to be queued in the operation queue. Meanwhile all references to 'self' diminish, except the one in the block. The block executes and eventually finishes and releases 'self' - possibly the last reference.
Additionally, in this case, it is required that 'self' must not be destroyed prematurely - that is, before message bar finished.
Doesn't break the cycle automatically - and isn't this warning over-alert?
Thanks for clarification!

> You can break this by having a strong reference to self that the block can manage independently.

> __block MyClass *      blockSelf = self;
> [self.operationQueue addOperationWithBlock:^{
> [blockSelf bar];
> blockSelf = nil;
> }];

Thank you Fritz for your answer.
But if I break the cycle and if I understand it correctly, 'self' won't be retained anymore within the block. If there are no more references to 'self' (except one possibly within the block), I fear 'self' will be destroyed before the block executes. I do require, though, that 'self' will be valid as long as the block is not finished.
Note: I'm using ARC in which case a retainable pointer declared with __block will be retained (as opposed to manual ref counting), so I should use __weak or __unsafe_unretained instead of __block to break the cycle (if that is what I have to do).
Andreas

转载于:https://my.oschina.net/abcMx/blog/201699

你可能感兴趣的文章
232. Implement Queue using Stacks
查看>>
Poj(1469),二分图最大匹配
查看>>
和菜鸟一起学linux之V4L2摄像头应用流程【转】
查看>>
spin_lock、spin_lock_irq、spin_lock_irqsave区别【转】
查看>>
删除 mac 垃圾桶内清除不掉的文件
查看>>
【响应式编程的思维艺术】 (5)Angular中Rxjs的应用示例
查看>>
/bin/bash^M: bad interpreter: No such file or dire
查看>>
python xml rpc
查看>>
Java设置以及获取JavaBean私有属性进阶
查看>>
db2表结构导出导入,数据库备份
查看>>
策略模式
查看>>
第二 周作业总结
查看>>
OrderOnline——项目概述
查看>>
POJ-2739(Water)
查看>>
【转】第三节 UNIX文件系统结构
查看>>
为什么sql里面not in后面的子查询如果有记录为NULL的,主查询就查不到记录
查看>>
Angular7里面实现 debounce search
查看>>
Linux 内核链表
查看>>
git学习------>Git 分支管理最佳实践
查看>>
括号和出栈所有序列问题
查看>>